/*
                       dP             dP                            dP                         
                        88             88                           88                         
.d8888b. .d8888b. .d888b88 .d8888b.    88d888b. dP    dP   .d8888b. 88d888b. .d8888b. 88d888b. 
88'  `"" 88'  `88 88'  `88 88ooood8    88'  `88 88    88   88'  `88 88'  `88 88ooood8 88'  `88 
88.  ... 88.  .88 88.  .88 88.  ...    88.  .88 88.  .88   88.  .88 88.  .88 88.  ... 88    88 
`88888P' `88888P' `88888P8 `88888P'    88Y8888' `8888P88   `88888P8 88Y8888' `88888P' dP    dP 
                                                     .88 
                                                 d8888P  
Go this way to kick his ass: http://www.douban.com/people/csser/
*/
//TODO: remove, test flash upload
//FormData = undefined;
//20130128  做三点修改：上传新地址替换，参数更替；flash上传增加md5验证，修复ie匿名列表点击页面下滑bug。
var _e = function(){};
if (typeof console != 'undefined') {
    _e = function(){
        var date = new Date()
            ,now = [ date.toLocaleTimeString(), '.', date.getMilliseconds(), ' -> ' ].join('');
        if( arguments.length === 1 && typeof arguments[0] !== 'object' ){
            console.log( '%c%d%o', 'font-size:12px;', now, arguments[0] );
        }else{
            console.info( '%c%d%o', 'font-size:12px;', now, arguments );
        }
    };
}


(function($, sohuHD, window, undefined){

  //1112 wyw 上传页同步到SNS功能  改自liuluying plugin/g.js 
  //优化：只出现一个style 
  //      异步添加的html适用。

  //20121117 增加g_flag = 0 flash上传   =1 html5上传。
    var g_flag ;
    //----end ----- 

    function UTSNS(){
        this.snsSendList = {};
        this.snsBoxs = null;
        
        var snsMe = this;
        var snsList = [
            {id : '6', en:"tsohu",position:[[-80,-40],[-80,-20],[-80,0]],name : '搜狐微博'}
            ,{id : '3', en:"sina",position:[[-0,-40],[-0,-20],[-0,0]],name : '新浪微博'}
            ,{id : '4', en:"qzone",position:[[-60,-40],[-60,-20],[-60,0]],name : 'QQ空间'}
            ,{id : '1', en:"renren",position:[[-20,-40],[-20,-20],[-20,0]],name : '人人网'}
            ,{id : '2', en:"qq",position:[[-40,-40],[-40,-20],[-40,0]],name : '腾讯微博'}
            ,{id : '8', en:"msn",position:[[-140,-40],[-140,-20],[-140,0]],name:'MSN'}
            ,{id : '7', en:"kaixin",position:[[-120,-40],[-120,-20],[-120,0]],name : '开心网'}
            ,{id : '5', en:"tianya",position:[[-100,-40],[-100,-20],[-100,0]],name : '天涯社区'}
        ];
        var snsHashList = {};
        function getSnsList(list,callback) {
            var tmpH = [];
            $.each(snsList,function(ii,o){
                var i = o.id;
                if(list.indexOf(i)>-1){
                    snsMe.snsSendList[i] = true;
                    tmpH.push('<a snsid="',i,'" tag="connectSNS',o.en,'" rel="',o.en,'" sns="send" style="background-position:',o.position[2][0],'px ',o.position[2][1],'px" title="取消同步" href="#" ></a>');
                }else{
                    snsMe.snsSendList[i] = false;
                    tmpH.push('<a snsid="',i,'" tag="connectSNS',o.en,'" rel="',o.en,'" sns="nobind" style="background-position:',o.position[0][0],'px ',o.position[0][1],'px" title="同步到',o.name,'" href="http://my.tv.sohu.com/user/connect/index.do?siteId=',i,'" target="_blank"></a>');
                }
                snsHashList[i] = o;
            });
           callback && callback.call(snsMe,tmpH.join('')); 
        }
       function drawSns(fn){
            messagebus.subscribe('com.sohu.login.userinfo',function(){
                var list = gUserParams.data || {};
                list = list.snsList || '';
                getSnsList(list,fn);
            },null,null,{cache:true});
            messagebus.subscribe('com.sohu.logout',function(){
                snsMe.hide();
            });
       }
       this.hide = function(){
            snsMe.snsBoxs.html('');
       }
       this.init = function(){
            if(snsMe.snsBoxs.length == 0){
                return this;
            }
            if($('#snsstyle').length == 0){
                $('head').append([
                    '<style id="snsstyle">'
                    ,'.commentToSNS {height: 20px;line-height: 20px;overflow: hidden;}'
                    ,'.commentToSNS .sns_tips{color: #333;float: left;}'
                    ,'.commentToSNS a{float: left;height: 20px;width: 20px;}'
                    ,'.commentToSNS a.sina , #commentToSNS a.qq, #commentToSNS a.renren'
                    ,',.commentToSNS a.sina_nosend , #commentToSNS a.qq_nosend, #commentToSNS a.renren_nosend'
                    ,',.commentToSNS a'
                    ,'{background: url(http://tv.sohu.com/upload/tv110421/images/ico/comment-sns.png) no-repeat 0 0;margin-left: 5px;}'
                    ,'.commentToSNS a.sina_nosend{background-position: 0 -20px;}'
                    ,'.commentToSNS a.sina_nobind{background-position: 0 -40px;}'
                    ,'.commentToSNS a.renren{background-position: -20px 0;}'
                    ,'.commentToSNS a.renren_nosend{background-position: -20px -20px;}'
                    ,'.commentToSNS a.renren_nobind{background-position: -20px -40px;}'
                    ,'.commentToSNS a.qq{background-position: -40px 0px;}'
                    ,'.commentToSNS a.qq_nosend{background-position: -40px -20px;}'
                    ,'.commentToSNS a.qq_nobind{background-position: -40px -40px;}'
                    ,'</style>'].join(''));
           }
           drawSns(function(snsHtml){
                if(snsHtml != ''){
                    snsMe.snsBoxs.html('<span class="mL20 l">同步到&nbsp;  </span><div class="commentToSNS icoBar l">'+snsHtml+'</div>').show();
                    snsMe.snsBoxs.find("[sns='send']").bind("click",function(e){
                        e.preventDefault();
                        snsMe.setStatus.apply($(this),[$(this).attr("snsid"),"nosend"]); 
                    });
                    snsMe.snsBoxs.find("[sns='nosend']").bind("click",function(e){
                        e.preventDefault();
                        snsMe.setStatus.apply($(this),[$(this).attr("snsid"),"send"]); 
                    });
                    
                }
            });
        }
        this.setStatus = function(snsid,status){
            if(this instanceof snsMe.setStatus){
                alert("please call a jqDom");
            }
            var boxs = snsMe.snsBoxs.find("[snsid='"+snsid+"']");
            if(status == "send"){
                if($(this).attr("sns") !=="nosend"){
                    return;
                }
                snsMe.snsSendList[snsid] = true;
                boxs.attr({
                    sns:"send"
                    ,style:"background-position:"+snsHashList[snsid].position[2][0]+"px "+snsHashList[snsid].position[2][1]+"px"  
                    ,title:"取消同步"
                }).unbind('click').bind('click',function(e){
                        e.preventDefault();
                        snsMe.setStatus.apply($(this),[$(this).attr("snsid"),"nosend"]); 
                });

            }
            else if(status == "nosend"){
                 if($(this).attr("sns") !=="send"){
                    return;
                }
                snsMe.snsSendList[snsid] = false;
                boxs.attr({
                    sns:"nosend"
                    ,style:"background-position:"+snsHashList[snsid].position[1][0]+"px "+snsHashList[snsid].position[1][1]+"px"  
                    ,title:"同步到"+snsHashList[snsid].name    
                }).unbind('click').bind('click',function(e){
                        e.preventDefault();
                        snsMe.setStatus.apply($(this),[$(this).attr("snsid"),"send"]); 
                });                   
            }
            else if(status == "nobind"){
                new Image().src = ['http://220.181.61.231/get.gif?type=comment2sns&url=' 
                    ,encodeURIComponent(location.href),'&_=',new Date().getTime()].join('');
            }
        } 
    };
    UTSNS.prototype.getIds = function(){
        var snsids = [];
        var t = this;
        $.each(t.snsSendList,function(i,o){
            if(o === true) {
                snsids.push(i);
            }
        });
        return snsids.join(',');
    };
    sohuHD.UTSNS = UTSNS;  
    //-----------end-------

	/*
	 *重写空间通用弹层,适应上传页弹层关闭特殊需求。
	 *wyw 20130304
	 * */
	var globalDepth=(function(){
		var depth=9999;
		return function globalDepth(){
			depth+=1;
			return depth;
		}
	})();

	sohuHD.popup=function(title,opts){
		var self={};
		var settings=$.extend(true,{
			overlay:true,			//是否显示遮罩，相当于模态弹层
			left:"center",			//弹层显示位置可以是number,也可是字符常量["center"|"left"|"right"|"top"|"bottom"] 
			top:"center",			//同上
			className:"",			//
			styleText:"",			//
			buttons:[				//自定弹层底部按钮
				{name:"确定",command:"dialog-close",className:"btn4a"}
			],
			content:""				//弹层内容html
			,reloadFlag:false			// 20130407 增加relaod判断
		},opts);
		var isIE6=($.browser.msie && $.browser.version =="6.0");
		var internalCommand=(function(){
			var cmdMap={ };
			var autoGenerateID=0;
			return {
				set:function(cmd,handler){
					cmdMap[cmd]=handler;	
				},
				get:function(cmd){
					return cmdMap[cmd]; 
				},
				autoGenerate:function(handler){
					autoGenerateID+=1;
					var cmd="AUTOGEN_"+autoGenerateID+"";
					this.set(cmd,handler);
					return cmd;
				}
			}
		})();

		var buttonsHtml=[];
		if(settings.buttons){
			buttonsHtml.push('<div class="blank20H"></div>');
			buttonsHtml.push('<div class="ta-c">');
			for(var i=0,item;item=settings.buttons[i];i++){
				if(typeof item.handler === "function"){ 
					item.command=internalCommand.autoGenerate(item.handler); 
				}
				if(i>0){
					buttonsHtml.push('<span class="mLR15"></span>');
				}
                // wyw 20121022 增加a标签src功能；
				buttonsHtml.push('<a href="',item.src ? item.src : '#','" class="',item.className,' fs14 f_yahei" data-cmd="',item.command,'"><span>',item.name,'</span></a>');
			}
			buttonsHtml.push('</div>');
			buttonsHtml.push('<div class="blank20H"></div>');
		}
		var contentHtml=settings.content;
		
		var overlayHtml="";
		if(settings.overlay){
			if(isIE6){
				overlayHtml='<iframe class="alp100" style="position:fixed;display:none;filter:Alpha(Opacity=\'0\');" frameborder="0" scrolling="no"></iframe>';
			}else{
				overlayHtml='<div class="alp100" style="position:fixed;display:none;"></div>';	
			}
		}

		var html=[overlayHtml
		,'<div class="wBox ',settings.className,'"   style="position:fixed;margin:0px;',settings.styleText,'">'
			,'<div class="wboxTop cfix png"><div class="wbWrap png"><div class="wbCont png"></div></div></div>'
				,'<div class="wboxMiddle cfix png">'
				,'<div class="wbWrap png">'
					,'<div class="wbCont png">'
						,'<div class="cfix">'
							,'<a title="关闭" data-cmd="dialog-close" class="ico1 r" href="#"></a>'
							,'<span class="color4 title">',title,'</span>'
						,'</div>'
						,contentHtml	
						,buttonsHtml.join('') 
					,'</div>'
				,'</div>'
			,'</div>'
			,'<div class="wboxBottom cfix png"><div class="wbWrap png"><div class="wbCont png"></div></div></div>'
		,'</div>'
		];
		var $win=$(window);
		var $dialog=$(html.join('')).appendTo('body')

		var $overlay=null;
		var $wbox=null;
		if(settings.overlay){
			$overlay=$($dialog.get(0));
			$wbox=$($dialog.get(1));
		}else{
			$wbox=$($dialog.get(0));
		}

		var _position=isIE6 ? "absolute" : "fixed";
		var _left=settings.left || "center";
		var _top =settings.top || "center";
		var _depth=globalDepth();
		
		var resize_scroll_handler=function(){
			if(settings.overlay){
				$overlay.coordinate(0,0,_position).css({width:$win.width(),height:$win.height()});
			}
			$wbox.coordinate(_left,_top,_position);
		}

		self.close=function(){
			$win.unbind("resize.dialog").unbind("scroll.dialog");	
			$dialog.remove()
		}

		self.open=function(){
			if(settings.overlay){
				$overlay.coordinate(0,0,_position).css({zIndex:_depth,width:$win.width(),height:$win.height()}).show();
			}
			$wbox.coordinate(_left,_top,_position).css({zIndex:_depth}).show();
			$win.bind("resize.dialog",resize_scroll_handler).bind("scroll.dialog",resize_scroll_handler);
		}

		internalCommand.set("dialog-close",function(sender,ev){
			sender.close();
			// wyw 20130407 增加reload判断
			if(settings.reloadFlag){
				//--wyw-新加20130304
				location.reload();
				//---end--
			}
			return false;
		});

		$wbox.click(function(ev){
			var $tar=$(ev.target);
			var $anchor=$tar.is("[data-cmd]") ? $tar : $tar.parent("[data-cmd]");	
			if($anchor.length>0){	
				var cmdFun=internalCommand.get($anchor.attr('data-cmd'));
				if(typeof cmdFun === "function"){
					ev.preventDefault();
					ev.stopPropagation();
					return cmdFun.call($anchor,self,ev);
				}
			}
		});
		self.open();	
		return self;
	};
	//-----end----
    var formatTime = function (sec, type) {
        var t = [];
        if (sec>0) {
            var m = Math.floor(sec/60), s = sec - m * 60;
            if (type) {
                t.push( m/10>=1 ? m+':' : '0'+m+':' );
                t.push( s/10>=1 ? s : '0'+s );
            } else {
                t.push( m/10>=1 ? m+'分' : '0'+m+'分' );
                t.push( s/10>=1 ? s+'秒' : '0'+s+'秒' );
            }
        } else {
            if (type) {
                t.push('00:00');
            } else {
                t.push('00分00秒');
            }
        }
        return t.join('');
    };

    var wordLimit = function(textObj, numObj, btn){
    //textObj: input对象
    //numObj: 字数显示对象, 根据input对象maxlength属性, 进行可输入数字计算
        if( !textObj.length || !numObj.length ) return;
        var len = $.trim( textObj.val() ).length;
        var max = parseInt( numObj.text() ) || 140;

        var check = function(){
            var newLen = $.trim( textObj.val() ).length;
            if( len == newLen ) return;
            len = $.trim( textObj.val() ).length;
            if( len <= max ){
                numObj.text( max-len ).removeClass('disabled');
                if(btn){
                    btn.removeAttr('disabled').removeClass('disabled');
                }
            }else{
                numObj.text( max-len ).addClass('disabled');
                if(btn){
                    btn.attr('disabled','disabled').addClass('disabled');
                }
            }
        };
        textObj.bind({
            focus : function(){
                textObj.timer = setInterval( check, 200 );
            }
            ,blur: function(){
                setTimeout( function(){
                    clearInterval( textObj.timer );
                }, 200 );
                textObj.timer = null;
            }
        });
    };

    var getFlashVersion = function(){
        var ver, major;
        if (document.all) {
            var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            if (swf) {
                ver = swf.GetVariable("$version");
                major = parseInt(ver.split(" ")[1].split(",")[0]);
            }
        } else {
            if (navigator.plugins && navigator.plugins.length > 0) {
                var swf = navigator.plugins["Shockwave Flash"];
                if (swf) {
                    var ver = swf.description.split(" ");
                    for (var i = 0; i < ver.length; ++i) {
                        if ( isNaN( parseInt(ver[i]) ) ) {
                            continue;
                        }
                        major = parseInt(ver[i]);
                    }
                }
            }
        }
        return {
            'm': major
            ,'ver': ver
        };
    };

    var getFileTitle = function(fileName){
        var t;
        try{
            t = (fileName).replace(/\.[^\.]+$/,'');
            if (t.length == 0) {
                t = fileName;
            }
        }catch(e){
            t = fileName;
        }
        return t;
    };

    var getFileType = function(fileName){
    //2012.08.06:mm
        var _types = {
            "wmv" : "video",
            "avi" : "video",
            "asf" : "video",
            "rm" : "video",
            "rmvb" : "video",
            "mpg" : "video",
            "mpeg" : "video",
            "3gp" : "video",
            "mov" : "video",
            "mp4" : "video",
            "f4v" : "video",
            "m4v" : "video",
            "dvix" : "video",
            "dv" : "video",
            "dat" : "video",
            "mkv" : "video",
            "flv" : "video",
            "vob" : "video",
            "ram" : "video",
            "qt" : "video",
            "divx" : "video",
            "cpk" : "video",
            "fli" : "video",
            "flc" : "video",
            "mod" : "video",
            "mp3" : "audio",
            "wma" : "audio",
            "wav" : "audio",
            "aac" : "audio",
            "mmf" : "audio",
            "amr" : "audio",
            "m4a" : "audio",
            "m4r" : "audio",
            "ogg" : "audio",
            "mp2" : "audio",
            "ape" : "audio",
            "flac" : "audio"
            //"mmf" : "audio",
            //"amr" : "audio",
        };

        var ext = '';
        if ( fileName.indexOf('.') > -1 ) {
            ext =  fileName.replace(/.*[.]/, '').toLowerCase();
        }
        return [_types[ext], '/', ext].join('');

    };
    /// add by yuelin  增加活动 id
    if(sohuHD.getUrlParam('actLabel')) {
       window.actLabel = sohuHD.getUrlParam('actLabel'); 
    }
    // 上传文件队列
    var fileQueue = [];
    //默认视频分类
    var CATEID =  window.categoriesId || 124; 
    var actLabel = window.actLabel || 0;
    //文件大小限制
    //20121112 wyw flash 上传文件大小
    var FILE_SIZE_LIMIT = 1024 * 1024 * 1024;
	//20121126 wyw 上传文件最小100K
	var FILE_SIZE_SMALL = 100 * 1024;
    //上传来源 flash:9, html5:8, anonymous:15
    var UPLOADFROM = 9;
    //同时上传视频数量, 从 0 开始计量
    var MAX_UPLOADING = 9;
    //文件分片大小
    var CHUNK = 1024 * 1024;
    //错误重试次数
    var OVERTIME = 20;
    //重试间隔
    var INTERVAL = 5000;
    //20130128 wyw 修改传入播放器参数。
    //计算MD5文件大小上限
	var ss = /.*?size=(.*$)/.exec(window.location.href)
    sohuHD.MD5_MAX = ss && ss[1]*1024*1024 || 100 * 1024 *1024;
    //----end---
    //上传统计日志
    var pingback = function(index, options){
        var info = fileQueue[index] || {};
        var opts = options || {};
        sohuHD.pingback(['http://up.hd.sohu.com.cn/stat.gif?'
                ,'type=', UPLOADFROM == 8 ? 'html5' : 'flash'
                ,info.vid ? '&vid=' + info.vid : ''
                ,info.file ? '&filesize=' + Math.ceil(info.file.size / 1024 / 1024) + 'M' : ''
                ,'&step=', opts.step ? opts.step : info.status
                ,info.vto ? '&vto=' + info.vto : ''
                ,info.percent ? '&percent=' + info.percent : ''
                ,UPLOADFROM !== 8 ? '&version=' + sohuHD.flashVer : ''
                ,'&userId=', UPLOADFROM == 15 ? 'anonymous' : (typeof sohuSpace != 'undefined' && (sohuSpace.owner.id || 'somebody'))
                ,'&msg=', opts.msg].join(''));
    };

    //更新上传任务总状态
    var updateQueue = function(){
        var init = 0, uploading = 0, success = 0, stop = 0;
        for (var i = 0; i < fileQueue.length; ++i) {
            if (i == 0 && fileQueue[i].status === 'init') {
                ++init;
                if($('#uploading').hasClass('hide')){
                    $('#upload').hide();
                    $('#uploading').show();
                }
            } else if (fileQueue[i].status === 'uploading') {
                ++uploading;
            } else if (fileQueue[i].status === 'success') {
                ++success;
            } else if (fileQueue[i].status === 'stop') {
                //fileQueue.splice(i, 1);
                ++stop;
            }
        }

        if (uploading > 0) {
            //$('.uploading-num').show();
            //$('.uploading-num strong').text( uploading );

            window.onbeforeunload = function (e) {
                for(var i = 0; i < fileQueue.length; ++i){
                    if (fileQueue[i] === 'uploading'){
                        //TODO 合并为一个请求？！
                        pingback(i, {step:'stop'});
                    }
                }
                return '视频正在上传中，您确定要关闭页面吗？\n72小时内可以断点续传该视频。';
            };
        } else {
            //$('.uploading-num').hide();
            window.onbeforeunload = null;
        }

        return {
            init: init
            ,uploading: uploading
            ,success: success
            ,stop: stop
        };
    };

    //更新表单数据
    var updateForm = function(index){ 
        var $form = $('#upload-list .video-form').eq(index);
        $.each($form.serializeArray(), function(i,o){
            if (o.name == 'tag') {
                fileQueue[index][o.name] = o.value.split(' ').slice(0, 5).join(' ');
            } else {
                fileQueue[index][o.name] = o.value;
            }
        });
    };
    
    //更新表单状态
    var checkForm = function(index){ 
        //TODO: 失去焦点等操作时调用此函数检查form是否有修改，做出相应的提示。
        var $form = $('.video-form').eq(index);
        if (fileQueue[index].plevel == 2) {
            $form.find('.video-password').closest('li').show();
        } else {
            $form.find('.video-password').closest('li').hide();
        }
    };

    //表单回填
    var autoFillForm = function(index, data, flag){
        //flag boolean 确定是否需要填title 
        var info = fileQueue[index];
        var $form = $('.video-form').eq(index);

        if(data){
            $.extend(info, {
                title: data.title
                ,introduction: data.introduction
                ,tag: data.tag
                ,categoriesId: data.categoriesId
                ,actLabel : data.actLabel
                ,plevel: data.plevel
            });
            //2012.08.09:mm
            if(g_flag == 0){
                ugcUploadPhoto.fillPhotoList(data);
            }
        }

        flag ? $form.find('.video-title').val('') : $form.find('.video-title').val(info.title);
        $form.find('.video-intro').val(info.introduction);
        $form.find('.video-tags').val(info.tag + ' ');
        $form.find('.video-cate').val(info.categoriesId).trigger('change');
        $form.find('.video-act').val(info.actLabel).trigger('change');
        
        /*
         * 微栏目上传带参数跳转，自动选择活动分类
         */
        try {
            var aid = location.search.match(/aid=([0-9]+)/)[1];
        } catch (e) {
            var aid = null;
        }
        if (aid) {
            $form.find('.video-act').val(aid).trigger('change');
        }
        try {
            var cid = location.search.match(/cid=([0-9]+)/)[1];
        } catch (e) {
            var cid = null;
        }
        if (cid) {
            $form.find('.video-cate').val(cid).trigger('change');
        }
        
        $form.find('.video-plevel').eq(info.plevel).prop('checked',true);
        //$form.find('.video-password').val(info.passwd);
        checkForm(index);
    };

    jQuery.ajax({type:"GET",dataType:"script",url:"http://tv.sohu.com/upload/jq_plugin/share.js",cache:true});

    var generateHTML = function(){
        updateQueue();
        //20121119 wyw 为音乐而添加
        //var html = [],con_i = [];
        var html = [],con_i = [],muc_html = [];

        for(var i = 0; i < fileQueue.length; ++i){
            if(fileQueue[i].status === 'init'){
                con_i.push(i);
                html.push('<div class="uBox" rel="',fileQueue[i].id,'">'
                    ,'<div class="upload-success hide">'
                        ,'<h3 class="fs18 f_yahei color4">'
                        ,fileQueue[i].file.name
                        ,'  上传成功！</h1>'
                        ,'<p class="fs14"><span>视频正在转码和审核中，稍等约10分钟就能观看了。</span>'
                        ,'<span class="hide">视频播放地址：<a class="play-url" href="#" target="_blank"></a></span>'
                        //20121115 wyw html5上传音乐
                        //,'<a class="btn10 f_hei" href="http://my.tv.sohu.com/user/video/list.do" target="_blank"><span>查看我的视频</span></a></p>'
                        ,'<a class="btn10 f_hei" href="http://my.tv.sohu.com/user/video/list.do" target="_blank"><span>查看我的视频</span></a>'
                        //20121119 wyw 音乐链接缩小范围
                        , /audio/.test(fileQueue[i].file.type) && (g_flag == 1) ? '<a class="btn10 f_hei musuc" href="#" target="_blank"><span>为音乐添加图片</span></a></p>' : '</p>'
                        //-----end----
                        //-------end-----
                    ,'</div>'
                    ,'<div class="upload-progress">'
                        ,'<h3 class="file-title fs14">',fileQueue[i].file.name,'</h3>'
                        ,'<div class="view">'
                        ,'<div style="width:0%" class="animate"></div>'
                        ,'<span class="upload-label">上传中...</span>'
                        ,'<em class="num">0%</em>'
                        ,'</div>'
                        ,'<div class="upload-cancel">'
                        ,'<a title="取消上传" class="btn10 f_hei" href="#"><span>X 取消/暂停</span></a>'
                        ,'</div>'
                    ,'</div>'
                    ,'<div class="upload-meta">'
                        ,'<span>速度：<em class="speed">--</em>KB/S</span>' 
                        ,' | <span>已上传：<em class="uploaded">0</em>M/<em class="file-size">',Math.ceil(fileQueue[i].file.size / 1024 / 1024),'</em>M</span>'
                        ,' | <span>剩余时间：<em class="time-left">计算中</em></span>'
                    ,'</div>'
                    ,'<div class="upload-err hide">'
                        ,'<a class="btn10 f_hei retry" href="#"><span>继续上传</span></a>'
                    ,'</div>'
                    ,'<div id="uploadPhotoTips" class="row2 cfix">' ,'</div>'
                    ,'<div>'
                        ,'<a href="#" class="btn12 toggle-form" '
                            , fileQueue[i].id == 0 
                                ? 'rel="open"><span>收起视频信息'
                                : 'rel="close"><span>展开填写视频信息'
                            , '</span></a><span class="tip"></span>'
                        //,'<h2 class="color4 fs14 d-i">填写视频信息</h2>'
                    ,'</div>'
                    ,'<form autocomplete="off" class="video-form cfix', fileQueue[i].id == 0 ? '' : ' hide' ,'" action="#">'                       	
                        ,'<div class="cfix">'
                            ,'<div class="l video-form-left">'
                                ,'<ul class="u">'
                                ,'<li>'
                                    //,'<p class="p1"><em>复制视频信息</em></p>'
                                    ,'<label><input type="checkbox" class="copylast" />复制上个视频信息来修改</label>'
                                ,'</li>'
                                ,'<li><p class="p1"><em>标题</em><span>最多50个字</span></p>'
                                ,'<input type="text" class="ipt video-title trigger" maxlength="50" name="title">'
                                ,'</li>'
                                ,'<li>'
                                ,'<p class="p1"><em>简介</em><span>讲讲这个视频的故事，让更多人了解。最多300字。</span></p>'
                                ,'<textarea class="video-intro trigger" maxlength="300" name="introduction"></textarea>'
                                ,'</li>'
                                ,'<li>'
                                ,'<p class="p1"><em>标签</em><span>每个标签最多10个字，最多5个标签；多个标签用空格分隔。</span></p>'
                                ,'<input type="text" value="" name="tag" maxlength="55" class="ipt video-tags trigger">'
                                ,'<p class="p2">热门标签：<span class="hot-tag"></span></p>'
                                ,'</li>'
                                ,'</ul>'
                            ,'</div>'
                            ,'<div class="l video-form-right">'
                                ,'<ul class="u">'
                                ,'<li>'
                                    ,'<p class="p1"><em>分类</em><span>合理的视频分类方便管理视频</span></p>'
                                    ,'<select class="video-cate trigger" name="categoriesId">'
                                        //,'<optgroup label="活动分类">'
                                        //,sohuHD.cateHtml.cateSpecial.join('')
                                        //,'</optgroup>'
                                        //,'<optgroup label="普通分类">'
                                        ,sohuHD.cateHtml.cateNormal.join('')
                                        //,'</optgroup>'
                                    ,'</select>'
                                ,'</li>'
                                ,'<li>'
                                    ,'<select class="video-act trigger" name="actLabel">'
                                        ,sohuHD.cateHtml.cateSpecial.join('')
                                        ,'<option selected="selected" value="0">选择你参加的活动</option>'
                                    ,'</select>'
                                ,'</li>'
                                ,'<li>'
                                ,'<p class="p1"><em>隐私</em><span>请选择隐私类型</span></p>'
                                ,'<label><input type="radio" class="video-plevel trigger" checked="checked" value="0" name="plevel">所有人可看</label>'
                                ,'<label><input type="radio" class="video-plevel trigger" value="1" name="plevel">互相关注可看</label>'
                                ,'<label><input type="radio" class="video-plevel trigger" value="2" name="plevel">密码</label>'
                                ,'<label><input type="radio" class="video-plevel trigger" value="3" name="plevel">仅自己可看</label>'
                                ,'</li>'
                                ,'<li class="hide">'
                                ,'<label><input type="text" class="ipt video-password trigger" value="" name="passwd"/></label>'
                                ,'</li>'
                                //20121025 wyw 增加添加到专辑功能
                                ,'<li>'
                                    ,'<p class="p1"><em>添加到专辑</em></p>'
                                    ,'<label><a class="xzzj btn1 va-t" href="#"><span class=" va-t">选择专辑</span></a><span class="mL15 mT">已加入<em class="color1"></em>个</span></label>'
                                ,'</li>'
                                //----------end-----------
                                //20121025 wyw  增加视频分享 
                                ,'<li>'
                                //,share_html
                                    ,'<p class="p1"><em>同步到：</em></p><div class="urlIcon">'
                                ,'</li>'
                                //----------end-----------
                                //,'<li class="tip"></li>'
                                ,'</ul>'
                            ,'</div>'
                        ,'</div>'
                        //musci photo begin
                        ,'<div class="upload-photo">'
                            //,'<div class="row1"></div>'
                            ,'<div class="blank20H"></div>'
                            ,'<div class="lines2"></div>'
                            ,'<div class="blank20H"></div>'
                            ,'<div class="upload-photo-tips">'
                                ,'<strong class="fs14">视频画面： </strong>'
                                ,'<a id="uploadPhotoBt" class="btn10 fs16 f_yahei mR15" href="#"><span>上传图片</span></a>'
                                ,' 支持图片格式为.jpg.png.bmp，最佳图片比例为4:3，可以拖拽排序。</div>'
                            ,'<div class="bg cfix">'
                                ,'共上传 <strong id="uploadPhotoCount" class="color4 fs14">0</strong> 张图片。图片翻页效果为 '
                               // 1113wyw  相册效果
                              //  ,'<select class="mLR6 va-m"><option>淡入淡出</option></select>'
                              //  ,'<input type="text" class="input5" value="5" disabled /> 秒钟变化一张图片，图片可循环播放，可以按ctrl多选图片。'

                                , '<select name="SwitchType" class="mLR6 va-m"><option value="0">淡入淡出</option>'
                                ,   '    <option value="1">动感光圈</option>'
                                ,   '    <option value="2">漂浮上升</option>'
                                ,   '    <option value="3">水滴绽放</option>'
                                ,   '    <option value="4">时间记忆</option>'
                                ,   '    <option value="5">从左到右</option>'
                                ,   '    <option value="6">中途分离</option>'
                                ,   '    <option value="7">星星希望</option>'
                                ,   '    <option value="8">鲜花祝福</option>'
                                ,'</select>'
                                //, '<input type="text" class="input5" value="5" /> 秒钟变化一张图片，图片可循环播放，可以按ctrl多选图片。'
                                , '<select name="SwitchTime"  class="mLR6 va-m" > <option value="5">5</option>'
                                ,' <option value="10">10</option>'
                                ,' <option value="20">20</option>'
                                ,'</select>'
                                ,'秒钟变化一张图片，图片可循环播放，可以按ctrl多选图片。'
                                //------end-----
                            ,'</div>'
                        ,'</div>'
                    // music photo end
                        ,'<div class="row3">'
                            ,'<ul class="upload-photo-list listFG cfix"></ul>'
                            //,'<button class="save-btn btn10 fs18 f_hei" type="submit"><span>保 存</span></button>'
                            ,'<div class="ta-c"><a href="#" class="btn14"><span><input type="submit" value="保 存" /></span></a></div>'
                        ,'</div>'
                    ,'</form>'
                ,'</div>');
            }
        }
        $('#upload-list').append(html.join(''));
        //wyw20121030 tosns
        messagebus.publish('com.sohu.sn',con_i);
    };

    //请求vid
    var getVid = function (index, callback){
        var info = fileQueue[index];
        //josnp方式参数var=tmp
        var params = ['m=add&outType=3&uploadFrom=',UPLOADFROM
                ,'&categoriesId=',CATEID
                ,'&actLabel=',actLabel
                ,'&title=',escape(info.title)
                ,'&tag=',escape(info.tag)
                ,'&introduction=',escape(info.title)
                ,'&plevel=',info.plevel
                ,'&videosize=',info.file.size
                ,sohuHD.gid ? '&gid=' + sohuHD.gid : ''
                //2012.08.09:mm add music type
                , info.file.type.indexOf('audio') > -1 ? '&videoType=20' : ''
           		,'&_=',$.now()
				//20130118 md5
				,'&videomd5=',info.md5  
				//end
            ].join('');

		// 20130118 wyw 更新上传接口为 my.tv.sohu.com/user/a/wvideo/save.do
       	// $.getJSON('/v.jhtml', params, function(msg){
	   	// my.tv.sohu.com/user/a/wvideo/save.do
        $.getJSON('/user/a/wvideo/save.do', params, function(msg){
			//----end--- 
			var tmparr = [''
				,'<div class="blank15H"></div>'
				];
            if (msg && msg.status == 1) {
					
                $.extend(info, {
                    vid: msg.id
                    ,vto: msg.vto
                    ,isold: msg.isold
                    ,status: 'uploading'
					//20130108 wyw 增加匿名uid
					,userId: msg.userId
					//---end---
                });

                $('#upload-list .uBox').eq(index).attr('vid',msg.id);

                //20121115 wyw html5上传音乐
                $('#upload-list .uBox').eq(index).find('.musuc').attr('href','http://my.tv.sohu.com/user/video/edit.do?id='+msg.id);
                //--------end--------
                
                pingback(index,{step:'getVid'});
                updateQueue();

                //回填表单
                if (msg.isold) {
                    autoFillForm(index, msg);
                } else {
                    autoFillForm(index);
                }

                //wyw 20121029 获取vid之后，去获取视频加入的专辑个数
                var t_url = '/user/a/playlist/list.do?pg=1&size=100&vid=' + msg.id;
                $.getJSON(t_url,function(mt){
                    var sum=0;
                    if(mt.data.count > 0){
                        var mtlist = mt.data.list;
                        for(var i=0,len=mtlist.length; i<len; i++){
                            mtlist[i].vidFlag ? sum++ : '';
                        }
                    }
                    $('#upload-list .uBox').eq(index).find('.xzzj').next().find('em').html(sum);
                });
                //-------end-----

				_e(msg.md5status);
                if (msg.videostatus < 20) {
                    if (msg.isold) {
                        var _tmp = '_vid' + $.now();
                        //NOTE: Flash 和 HTML5 都采用单线程上传
                        $.getScript([msg.vto,'?type=3&outType=3&id=',msg.id,'&varname=',_tmp].join(''), function(){
                            var data = window[_tmp];
                            var partNo = [];
                            if (data && data.code == 100){
                                partNo = data.partNo.split(',');
                            }
                            //NOTE: partNo = '1,2,3,4,5,' , 没错，最后面有个点, 分片从1开始的，不是0。
                            //修正为从0开始，提交分片参数的时候+1
                            //断点续传是从下一个分片开始上传的, 所以是5-1+1分片开始上传的，最小的情况是['1',''](1-1+1)
                            info.start = partNo.length > 2 ? parseInt(partNo[partNo.length - 2]) : 0;
						//	console.log(partNo);
						//	console.log(info.start);
                            callback();
						//	console.log(info.start);

                        });
                    } else {
                        callback();
                    }
                } else {
                    //NOTE: 已上传过的文件不再重新上传，进度条100%然后让用于编辑视频信息
                    info.startTime = $.now() - 1000;
                    info.status = 'success';
                    info.uploaded = info.file.size;
                    updateProgress(index, 1000)();
                    //updateQueue();
                    //wyw 解决上传100%bug
                    uploadSuccess(index);
                    pingback(index);
                }
            } else {
                _e('server error: ',msg);
                pingback(index,{step:'getVidErr',msg: 'server.error.code.' + msg.status});
				//20130407 wyw 更改错误提示语
                if (msg.status === 7) {
                    //sohuHD.alert('因为您多次发布违规内容，账号已被冻结。');
                   // sohuHD.alert('对不起，您的账号已被封禁，无法上传视频，可点击申请解封。','ico32');
				   // setTimeout(function(){
				   // 	location.reload();
				   // }, 3000);
					tmparr.push(
							'<div class="fs14"><span class="ico-wran1 l  mT6"></span>对不起，您的账号已被封禁，无法上传视频！</div>'
							,'<div class="fs12 mL20">'
							,	'你可以：<a class="mL6" href="http://tv.sohu.com/upload/feedback/feedback.html" target="_blank">申请解封</a>。'
							,'</div>');
					sohuHD.popup('',{
						content:tmparr.join('')
						,buttons:[				//自定弹层底部按钮
							{name:"确定",command:'data-null',className:"btn4a"
								,handler:function(){
									location.reload();
								}
							}
						]
						,reloadFlag:true
					});
				//----end---
                } else if (msg.status === 9) {
                    sohuHD.alert('您已经匿名上传了5个视频，登录上传更多。','ico32');
					setTimeout(function(){
						location.reload();
					}, 3000);
                } else if (msg.status === 10) {
                    //sohuHD.alert('文件名含有敏感词，请修改文件名后再上传。');
                    sohuHD.alert('内容中含有国家有关部门所禁止的内容，请您删除后再保存！','ico32');
					setTimeout(function(){
						location.reload();
					}, 3000);
				// wyw 20130228 重复上传提示 、重申功能
                } else if (msg.status === 30) {
					tmparr.push(
							'<div class="fs14"><span class="ico-wran1 l  mT6"></span>您已上传过该视频，视频正在审核中，无需重复上传。</div>'
							,'<div class="fs12 mL20">'
							,	'你可以：<a class="mL6" href="http://my.tv.sohu.com/user/video/list.do" target="_blank">查看我的视频\>\></a>'
							,'</div>');
					sohuHD.popup('',{
						content:tmparr.join('')
						,buttons:[				//自定弹层底部按钮
							{name:"确定",command:'data-null',className:"btn4a"
								,handler:function(){
									location.reload();
								}
							}
						]
						,reloadFlag:true
					});
                } else if (msg.status === 37) {
					tmparr.push(
						'<div class="fs14 vst37"><span class="ico-wran1 l  mT6"></span>您已上传过该视频，由于该视频违反《视频内容发布协议》，未通过审核！</div>'
						,'<div class="fs12 mL20 vst37">'
						,	'你可以：<a class="mL6" href="http://tv.sohu.com/upload/hdfeedback/index.jsp?#46" target="_blank">查看原因</a>，或申请再次审核。'
						,'</div>'
						,'<div class="fs14 vst37 ta-c hide"><span class="ico-ok1"></span>申请成功。</div>'
						,'<div class="fs14 vst37err ta-c hide"><span class="ico-wrong1"></span>出错鸟。</div>'
						,'<div class="fs14 vst37dob ta-c hide"><span class="ico-wran1"></span>不能重复申请重审任务。</div>');
					sohuHD.popup('',{
						content:tmparr.join('')
						,buttons:[				//自定弹层底部按钮
							{name:"申请审核",command:'data-null',className:"btn4a"
								,handler:function(){
									$.ajax({
										url:'http://my.tv.sohu.com/user/a/reaudit/save.do'
										,type:'get'
										,data:{
											vid:msg.id
											,userId:sohuSpace.owner.id
											,reason:'上传页申请重申'}
										,success:function(lmsg){
											if(lmsg&&lmsg.status == 1){
												$('.vst37').toggle();
												$('.wBox .btn4a').parent().html('<a data-cmd="dialog-close" class="btn4a fs14 f_yahei" href="#"><span>确定</span></a>');
											}else if(lmsg&&lmsg.status == 0){
												$('.vst37').hide();
												$('.vst37dob').show();
												$('.wBox .btn4a').parent().html('<a data-cmd="dialog-close" class="btn4a fs14 f_yahei" href="#"><span>确定</span></a>');
											}else {
												$('.vst37').hide();
												$('.vst37err').show();
												$('.wBox .btn4a').parent().html('<a data-cmd="dialog-close" class="btn4a fs14 f_yahei" href="#"><span>确定</span></a>');
											}
											setTimeout(function(){
												location.reload();
											}, 3000);
										}
										,dataType:'json'
										,error:function(){
											$('.vst37').hide();
											$('.vst37dob').show();
											$('.wBox .btn4a').parent().html('<a data-cmd="dialog-close" class="btn4a fs14 f_yahei" href="#"><span>确定</span></a>');
											setTimeout(function(){
												location.reload();
											}, 3000);
										}
									});
								}}
						]
						,reloadFlag:true
					});
                } else if (msg.status === 40) {
					tmparr.push(
						'<div class="fs14"><span class="ico-wran1 l  mT6"></span>您已上传过该视频，无需重复上传。</div>'
						,'<div class="fs12 mL20">'
						,	'点击观看：<a class="mL6" href="',msg.errmsg.url,'" target="_blank">',msg.errmsg.title,'</a>'
						,'</div>');
					sohuHD.popup('',{
						content:tmparr.join('')
						,buttons:[				//自定弹层底部按钮
							{name:"确定",command:'data-null',className:"btn4a"
								,handler:function(){
									location.reload();
								}
							}
						]
						,reloadFlag:true
					});
					//-----end----
                }
				//20130403 wyw新增错误提示
				else if(msg.status == 2){
                    sohuHD.alert('您还未登录视频空间，请先登录。','ico32');
					setTimeout(function(){
						location.reload();
					}, 3000);
				}
				else if(msg.status == 8){
                    sohuHD.alert('服务器正在卯足劲处理，请您稍等片刻后再试。','ico32');
					setTimeout(function(){
						location.reload();
					}, 3000);
				}
				//---end---
			   	else {
                    //TODO 批量上传提示用弹窗太暴力，应该用更温和的提示, 上传区域用醒目文字提示
                    sohuHD.alert('服务器开小差了，请稍后再试');
					setTimeout(function(){
						location.reload();
					}, 3000);
                }
            }
        }).error(function(msg){
            _e('post error: ', msg);
            pingback(index,{step:'getVidErr',msg: 'response.status.400'});
            sohuHD.alert('服务器开小差了，请稍后再试');
            setTimeout(function(){
                location.reload();
            }, 1000);
        });
    };

    //更新总进度
    var overallProgress = function(){
        var percent = 0, num = 0;
        for(var i = 0; i < fileQueue.length; ++i){
            if (fileQueue[i].status == 'init' || fileQueue[i].status == 'uploading') {
                ++num;
                percent += fileQueue[i].percent;
            }
        }
    };

    //更新进度条等信息
    var updateProgress = function(index, duration){
        var info = fileQueue[index]
            ,$li = $('#upload-list .uBox').eq(index)
            ,loader = $li.find('.animate')
            ,loaderTxt = $li.find('.num')
            ,speed = $li.find('.speed')
            ,uploaded = $li.find('.uploaded')
            ,timeLeft = $li.find('.time-left')
            ,duration = duration || 150;

        var percent, speedTxt, timeLeftTxt = -1; 

        return function(){
            percent = Math.round(info.uploaded / info.file.size * 100);
            speedTxt =  (info.loaded || CHUNK) / ($.now() - info.startTime + 1);
            if (percent > info.percent || percent == 100) {
                info.percent = percent;
                //uploaded文件已上传部分 loaded该分片已上传部分, flash上传 loaded == CHUNK
                timeLeftTxt = Math.ceil((info.file.size - info.uploaded) / speedTxt / 1000); 
                //loader.width(percent + '%');
                loader.stop(true,true).animate({ 'width': percent + '%' }, duration, 'linear');
                //loader.stop(true,true).animate({ 'width': percent + '%' }, duration, 'linear', function(){
                //    if (info.uploaded == info.file.size) {
                //        $li.find('.play-url').attr('href','/u/vw/' + info.vid).text('http://my.tv.sohu.com/u/vw/' + info.vid);
                //        $li.find('.upload-success').show();
                //        $li.find('.upload-progress').hide();
                //        $li.find('.upload-meta').hide();
                //        //隐藏flash
                //        if(info.status == 'success'){
                //            $('#uploader').remove();
                //        }
                //    }
                //}); 
                loaderTxt.text(percent + '%');
                uploaded.text(Math.ceil(info.uploaded / 1024 / 1024));
            }
            timeLeft.text(timeLeftTxt < 0 ? '计算中' : formatTime(timeLeftTxt));
            speed.text(Math.round(speedTxt));
        }
    };

    //上传错误
    var uploadErr = function(index, callback){
        fileQueue[index].status = 'error';
        var $li = $('#upload-list .uBox').eq(index);
        var $view = $li.find('.view');
        var $label = $li.find('.upload-label');
        var $err = $li.find('.upload-err');
        var $cancel = $li.find('.upload-cancel');

        $cancel.hide();
        $view.addClass('view-err');
        $err.show();
        $label.text('通常网络不佳会上传失败，请稍后尝试继续上传。');
        $li.find('.speed').text('--');
        $li.find('.time-left').text('--分--秒');

        $err.find('.retry').click(function(ev){
            ev.preventDefault();
            $err.hide();
            $view.removeClass('view-err');
            $label.text('上传中...');
            $cancel.show();

            fileQueue[index].status = 'uploading';
            fileQueue[index].overtime = 20;
            callback();
        });
        pingback(index);
    };

    //取消上传
    var stopUpload = function (index) {
        fileQueue[index].status = 'stop'; 
        fileQueue.xhr && fileQueue[index].xhr.abort();

        $('#upload-list .uBox').eq(index).slideUp('slow', function(){
            if (fileQueue.length == updateQueue().stop) {
                $('#uploading').fadeOut('fast', function(){
                    $('#upload-list').html('');
                    $('#upload').show();
                    fileQueue = [];
                    if (UPLOADFROM != 8){
                        updateCoords.btn = $('#upload .layer-1 button');
                        sohuHD.flashDom.width = updateCoords.btn.outerWidth();
                        sohuHD.flashDom.height = updateCoords.btn.outerHeight();
                        updateCoords.up();
                    }
                });
            }
        }).prev('.blank20H').hide();

        pingback(index, {step:'cancel'});
        // 20130128 wyw
       // if(g_flag == "0"){
       //     flashDom.deleteUpload();
       //     window.location.reload();
       // }
    };

    //2012.08.06:mm
    //request type=7 max times
    sohuHD.requestCount = 0;
    //上传成功
    var uploadSuccess = function (index) {
        var info = fileQueue[index];
        if (!info) {
            return;
        }
        var $li = $('#upload-list .uBox').eq(index);

        info.uploaded = info.file.size;
        var tmp = '_vid' + $.now();
        var url = [info.vto, '?type=7&outType=3&id=', info.vid ,'&size=', info.file.size
                //其实是filetype...e.g. '.mp4'
                ,'&file=', info.file.name.replace(/.*[.]/, '.')
                ,'&varname=', tmp ].join('');

        //上传完毕发送type=7的请求才算是一个完整上传
        $.getScript(url ,function(){
            var data = window[tmp];
            if (data && data.code == 100) {
                info.status = 'success';
                updateQueue();
                pingback(index);
				//20130108 wyw 新播放地址
                //$li.find('.play-url').attr('href','/u/vw/' + info.vid).text('http://my.tv.sohu.com/u/vw/' + info.vid);
                $li.find('.play-url').attr('href','/us/' + info.userId + '/' + info.vid + '.shtml').text('http://my.tv.sohu.com/us/' + info.userId + '/' + info.vid + '.shtml');
				//----end--- 
                $li.find('.upload-success').show();
                $li.find('.upload-progress').hide();
                $li.find('.upload-meta').hide();
            //2012.08.06: mm
            //add max request repeat times
            } else if (sohuHD.requestCount < 10){
                setTimeout(function(){
                    uploadSuccess(index);
                    ++sohuHD.requestCount;
                },500);
            //TODO: remove test
            } else {
                info.status = 'success';
                updateQueue();
                pingback(index);
				//20130108 wyw 新播放地址
                //$li.find('.play-url').attr('href','/u/vw/' + info.vid).text('http://my.tv.sohu.com/u/vw/' + info.vid);
                $li.find('.play-url').attr('href','/us/' + info.userId + '/' + info.vid + '.shtml').text('http://my.tv.sohu.com/us/' + info.userId + '/' + info.vid + '.shtml');
				//---end---
                $li.find('.upload-success').show();
                $li.find('.upload-progress').hide();
                $li.find('.upload-meta').hide();
            }

			//20130122 wyw 上传完成后 释放内存
			if(g_flag == 0 ){
				$(sohuHD.flashDom).remove();
			}
			//-----end----
        });
    };

    //通过匿名上传的视频列表
    var getGidList = function(){
		// 20130118 wyw 更新上传接口为 my.tv.sohu.com/user/a/wvideo/save.do
        //$.getJSON('/v.jhtml?m=listAnonyMous&gid=' + sohuHD.gid + '&_=' + $.now(), function(msg){
        //$.getJSON('/user/a/rvideo/listAnonyMous.do?&gid=' + sohuHD.gid + '&_=' + 1359445317612, function(msg){
        $.getJSON('/user/a/rvideo/listAnonyMous.do?&gid=' + sohuHD.gid + '&_=' + $.now(), function(msg){
			//----end ---- 
            //TODO 只显示成功
            if(msg.count > 0){
                //var img;
                var data;
                var html = ['<div class="gid-sub fs14">您已经匿名上传了 <span class="num">',msg.count
                        ,'</span> 个视频，匿名最多上传 5 个视频，登录上传更多。'
                        ,'<a class="btn12 show-gid-list" href="#" rel="close"><span>展开列表导入视频</span></a>'
                        ,'</div><div class="gid-list hide">'];
                for (var i = 0; i < msg.data.length; ++i) {
                    data = msg.data[i];
                    if (data.status == 40){
                        html.push('<div class="list cfix"><div class="photo l">'
                                ,'<img width="97" height="72" alt="',data.title,'" src="'
                                //20121121 wyw 解决无url
                                ,data.cusCoverURL == "" ? 'http://tv.sohu.com/upload/static/space/skin/images/fox-s.jpg' : data.cusCoverURL
                                //------end------
                                ,'" class="bd">'
                                ,'</div><div class="txt l"><h3>',data.title,'</h3>'
                                ,'<p><span>上传时间：',new Date(data.uploadTime).asString('yyyy-mm-dd'),'</span></p>'
								//20130107 wyw 新版上传页
                                //,'<p><a href="/u/vw/',data.id,'" class="btn10" target="_blank"><span>播 放</span></a> <em rel="'
                                ,'<p><a href="'
								,data.userId ? '/us/'+data.userId+'/'+data.id+'.shtml' :'/u/vw/'+data.id
								,'" class="btn10" target="_blank"><span>播 放</span></a> <em rel="'
								//----end----
                                ,data.id,'" class="btn10 export"><span>导入到我的视频</span></em></p></div></div>');
                    }
                    //img = 'http://js1.my.tv.sohu.com.cn/ppp/mv/styles/index/images/default/';
                    //switch(data.status){
                        //case 10 :
                            //img += 'uping.jpg';
                            //break;
                        //case 11 :
                            //img += 'uppause.jpg';
                            //break;
                        //case 12 :
                            //img += 'upfail.png';
                            //break;
                        //case 21 :
                            //img += 'uncing.jpg';
                            //break;
                        //case 22 :
                            //img += 'encfail.png';
                            //break;
                        //case 30 :
                            //img += 'auding.jpg';
                            //break;
                        //case 37 :
                            //img += 'audfail.png';
                            //break;
                        //case 40 :
                            //img = data.cusCoverURL;
                            //break;
                        //default:
                            //img += 'default.jpg';
                    //}
                }
                html.push('</div>');

                $('#gid-list').html(html.join('')).show();
                updateCoords.up();

              //  wyw 20130128 修复ie下展开匿名列表 下边页面不下滑(ie6除外)。
                if(sohuHD.isIE6){
                    $('.show-gid-list').click(function(ev){
                        ev.preventDefault();
                        var me = $(this);
                        $('.gid-list').slideToggle('slow',function(){
                            if (me.attr('rel') == 'open'){
                                me.attr('rel','close').find('span').text('展开填写视频信息');
                            } else {
                                me.attr('rel','open').find('span').text('收起填写视频信息');
                            }
                            updateCoords.up();
                        });
                    });
                }else{
                    $('.show-gid-list').click(function(ev){
                        ev.preventDefault();
						if(sohuHD.isIE){
							$('#upload').removeClass('rel');
							$('#uploading').removeClass('rel');
							$('#uploading div').first().removeClass('rel');
							$('.flash-upload').removeClass('layer');
						}
                        var me = $(this);
                        updateCoords.up();
                        $('.gid-list').slideToggle('fast',function(){
                            if (me.attr('rel') == 'open'){
                                me.attr('rel','close').find('span').text('展开填写视频信息');
                            } else {
                                me.attr('rel','open').find('span').text('收起填写视频信息');
                            }
							if(sohuHD.isIE){
								$('.flash-upload').addClass('layer');
								$('#uploading div').first().addClass('rel');
							}
                            updateCoords.up();
                        });
                    }); 
                }
				//-----end----

                $('.export').click(function(){
                    var $li = $(this).closest('.list'); 
                    if (!PassportSC.cookieHandle()) {
                        //TODO 优化提示
                        sohuHD.alert('登录之后才能导入视频');
                    } else {
						// 20130118 wyw 更新上传接口为 my.tv.sohu.com/user/a/wvideo/save.do
                        //$.post('/v.jhtml',{
                               // m:'importAnonyMous'
                        $.post('/user/a/wvideo/importAnonyMous.do',{
							//----end---- 
                                gid : sohuHD.gid   
                                ,vid : $(this).attr('rel')
                            },function(msg){
                                var dialogHtml;
                                if(msg.rs == true){
                                    //TODO: 导入成功
									if(sohuHD.isIE){
										$('.flash-upload').removeClass('layer');
										$('#uploading div').first().removeClass('rel');
									}
                                    $li.slideUp('slow', function() {
                                        var num = parseInt($('.gid-sub .num').text()) - 1; 
                                        $('.gid-sub .num').text(num);
                                        if(num == 0){
											if(sohuHD.isIE){
												$('.flash-upload').removeClass('layer');
												$('#uploading div').first().removeClass('rel');
											}
                                            $('.gid-list').slideUp('fast',function(){
												if(sohuHD.isIE){
													$('.flash-upload').addClass('layer');
													$('#uploading div').first().addClass('rel');
												}
                                                updateCoords.up();
                                            });
                                        }
										if(sohuHD.isIE){
											$('.flash-upload').addClass('layer');
											$('#uploading div').first().addClass('rel');
										}
                                        updateCoords.up();
                                    });
                                }else{
                                    //TODO: 导入失败
                                    sohuHD.alert('导入失败');
                                }
                            },'json');
                    }
                });
            }
        });
    };

    // 更新坐标
    var updateCoords = {
        btn: false
        ,target: false
        ,up: function(){
            //2012.08.20:mm
            if (this.btn && this.target) {
                this.target.css({
                    left: this.btn.offset().left
                    ,top: this.btn.offset().top
                });
            }
        }
    };

    // flash 初始化上传
    var initFlash = function () {
        var flashVer = getFlashVersion().ver;
        if (flashVer == undefined) {
            if (confirm('您的浏览器未安装 Flash Player 组件，无法正常使用上传功能，请安装。')) {
                sohuHD.redirect('http://get.adobe.com/cn/flashplayer/otherversions/', '_blank');
            }
        } else {
            flashVer = typeof flashVer != 'string' ? flashVer.join('') : flashVer;
            if (getFlashVersion().m < 10){
                if (confirm('您的 Flash 版本过低，无法使用上传组件。\n请升级 Flash 享受更多功能。')) {
                    sohuHD.redirect('http://get.adobe.com/cn/flashplayer/otherversions/', '_blank');
                }
            }
        }
        sohuHD.flashVer = flashVer;

        //开始下载
        pingback(0, {step: 'flashInit_1', msg:'flash.start.upload'});

        var visualBtn = $('#upload .layer-1 button');
        var height = visualBtn.outerHeight();
        var width = visualBtn.outerWidth();
        //20130128 wyw 修改传入播放器参数。
        var swf = 'http://tv.sohu.com/upload/static/space/skin/swf/uploader.swf?uploader=sohuHD.uploader&MD5Max='+sohuHD.MD5_MAX+'&mouseOver=sohuHD.mouseEvent.enter&mouseOut=sohuHD.mouseEvent.leave&_=20130305';
        //var swf = 'http://tv.sohu.com/upload/static/space/skin/swf/uploader.swf?uploader=sohuHD.uploader&skinNum=0&mouseOver=sohuHD.mouseEvent.enter&mouseOut=sohuHD.mouseEvent.leave&_=20120821';
        //----end----
        var flashHtml = ['<object width="',width,'" height="',height,'" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" name="uploader_ob" id="uploader_ob">'
            ,'<param value="always" name="allowScriptAccess" />'
            ,'<param value="',swf,'" name="movie" />'
            ,'<param value="high" name="quality" />'
            ,'<param value="false" name="allowFullScreen" />'
            ,'<param value="transparent" name="wmode" />'
            ,'<param value="" name="flashvars" />'
            ,'<embed width="',width,'" height="',height,'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="false" allowscriptaccess="always" quality="high" flashvars="" src="',swf,'" name="uploader_em" id="uploader_em">'
            ,'</object>'].join('');

        var uploader = $('<div id="uploader"></div>');
        var off = visualBtn.offset();
        uploader.css({
            position:'absolute'
            ,'width' : width
            ,'height' : height
            ,left: off.left
            ,top: off.top
            ,'z-index': 10
        }).appendTo($('body'));

        uploader.html(flashHtml);

        var flashDom = $.browser.msie ? $('#uploader_ob')[0] : $('#uploader_em')[0];
        sohuHD.flashDom = flashDom;
        var progress;
        updateCoords.btn = visualBtn;
        updateCoords.target = uploader;
        $(window).resize(function() {
            updateCoords.up();
        });

        //20130128 wyw opts==init或者opts==calcu 时候初始化页面。
        var com_init = function(opts){
			//wyw 20130318 增加flash 上传空文件返回undefined判断。 暂时解决方法
			if(!opts.size){
                flashDom.deleteUpload();
                sohuHD.alert('不能上传空文件');
			//----end-----
			}else if((getFileType(opts.title).indexOf('video') == -1) && (getFileType(opts.title).indexOf('audio') == -1) ){
                flashDom.deleteUpload();
                sohuHD.alert('您上传的不是媒体文件');
			}else if (opts.size > FILE_SIZE_LIMIT) {
                flashDom.deleteUpload();
               // sohuHD.alert('视频太大了。');
                sohuHD.alert('<a href = "http://my.tv.sohu.com/user/video/super_upload.do">视频容量有点大。 可以安装搜狐影音上传到10Gb视频。</a>');
            } else if (opts.size == 0) {
                flashDom.deleteUpload();
                sohuHD.alert('不能上传空文件');
                //20121126 wyw 文件最小限制20k
            } else if (opts.size < FILE_SIZE_SMALL) {
                flashDom.deleteUpload();
                sohuHD.alert('您上传的媒体文件太小了');
                //-------end------
            }else {
                if (fileQueue.length > 0) {
                    return;
                }

                var fileType = getFileType(opts.title);
                //TODO remove test
                //fileType = 'audio/mp3';

                fileQueue.push({
                    id: fileQueue.length
                    ,status: 'init'
                    ,file : {
                            name: opts.title
                            ,size: opts.size
                            ,type : fileType
                        }
                    ,title: sohuHD.strSub(getFileTitle(opts.title),60)
                    ,categoriesId: CATEID
                    ,actLabel : actLabel
                    ,tag: sohuHD.strSub(getFileTitle(opts.title),8)
                    ,introduction: ''
                    ,plevel: 0
                    ,passwd: null
                    ,save: false
                    ,xhr: false
                    ,start: 0
                    ,percent: 0
                    ,overtime: OVERTIME
                    ,timer: null
                });

                //生成 HTML;
                generateHTML();
                //2012.08.09:mm
                //music photo
                if (/audio/.test(fileType)) {
                    //try{
                    ugcUploadPhoto.isAudio = true;
                    $('#uploadPhotoTips').html(['<span class="ico-wran1 l"></span>'
                        ,'<div>'
                            ,'<h3 class="fs16">您上传的是音频文件!</h3>'
                            ,'<p>请'
                            ,PassportSC.cookieHandle() ? '' : '<font style="color:red;"> 登录 </font>'
                            ,'上传图片设置视频内容和封面！创作属于自己的相册视频</p>'
                        ,'</div>'].join(''));
                    ugcUploadPhoto.initPhotoUpload({
                        vid : fileQueue[0].vid,
                        photoList : $('#upload-list ul.upload-photo-list'),
                        SType:$('#upload-list select[name="SwitchType"]'),
                        STime:$('#upload-list select[name="SwitchTime"]')
                    });
                    //}catch( ex ) {alert(ex.message);}
                }
            }
        };
        //---------end ----------------
        
        // flash 上传调用的接口，通过uploader传函数名，默认sohuHD.uploader
        // Flash API
        // flashDOM.deleteUpload : 取消上传，通知 flash 终止上传、释放内存、初始化操作
        // flashDOM.uploadFun : 请求 vid 成功之后，调用此接口，开始上传
        // flashDOM.xhr : 通过 flash 来实现跨域 POST
        //        sohuHD.callback = function(data){
        //            _e(data);
        //        }
        //        flashDom.xhr({
        //            url: 'http://my.tv.sohu.com/v.jhtml'
        //            ,data:[
        //                {key: 'm', value: 'listAnonyMous'}
        //                ,{key: 'gid', value: '48412a54-96b5-6884-2826-27C2E919ae12'}
        //                ,{key: '...', value: '...'}
        //            ]
        //            ,callback: 'sohuHD.callback'
        //        });

        sohuHD.uploader = function(options){
            var opts = $.extend({
                cancel : false
                //20130118 wyw 
                ,md5: ''
            }, options);
            _e("flash info:" + opts);

          //20130131 wyw 取消上传  发现firefox 18.0.1对执行confirm 慢的无法忍受，现更新为兼容模式：
		  //					   ie下使用浏览器弹窗confirm，非ie使用js模拟。
		  //					   现在取消在计算MD5时候不生效。因为播放器此时取消容易崩溃。
          // 取消上传
          //  if (opts.cancel) {
          //      if (confirm('您确认要取消或暂停本次上传吗？\n您可以在72小时内，按上次进度继续上传。')) {
          //          flashDom.deleteUpload();
          //          stopUpload(0);
          //          return;
          //      }
          //  }
		  	if(opts.cancel){
				if(sohuHD.isIE){
					if (confirm('您确认要取消或暂停本次上传吗？\n您可以在72小时内，按上次进度继续上传。')) {
						flashDom.deleteUpload();
						stopUpload(0);
						return;
					}
				}else{
					sohuHD.popup("",{
						buttons:[{
							name:"确定",
							handler:function(sender){ 
								sender.close();	
								$(flashDom).remove();
								stopUpload(0);
								initFlash();
							},
							className:"btn4a"
						}, { 
							name:"取消",
							command:"dialog-close",
							className:"btn4"
						}],	
						content:[''
							,'<div class="blank20H"></div>'
							,'<div class="cfix mL15">'
								,'<span class="fico3 va-m l mL15"></span>'
								,'<div class="l">'
									,'<strong class="fs14 color4">您确认要取消或暂停本次上传吗？</strong>'
									,'<div><span>您可以在72小时内，\n按上次进度继续上传。</span></div>'
								,'</div>'
							,'</div>'
						].join('')
						,reloadFlag:true
					});
				}
			}
			//----end-----
            //匿名上传使用gid
            if (opts.gid) {
                sohuHD.gid = opts.gid;
                getGidList();
                pingback(0, {step: 'flashInit_3', msg: 'flash.to.js' });
                return;
            }

            //20130123 wyw md5页面提示
 		   	if (opts.status == "calcu") {
                com_init(opts); 
                (function(opts){
                    var strarr = [];

                    if($('#calculateMd5').length > 0){
                        strarr.push('正在加载文件&计算MD5...');
                        $('#calculateMd5').html(strarr.join());
                        return;
                    }
                    strarr.push('<span id="calculateMd5">');
                    strarr.push('正在加载文件&计算MD5...</span>');
                    $(strarr.join('')).insertBefore('.upload-meta');
                    $('.upload-meta').hide();
                    return;
                })(opts);
                //----end----
			} else if (opts.status == 'uploading' && fileQueue[0].uploaded != opts.uploaded) {
                fileQueue[0].uploaded = opts.uploaded;
                progress();
                fileQueue[0].startTime = $.now();
            } else if (opts.status == 'error') {
                uploadErr(0, function(){
                    flashDom.resumeUpload();
                });
            } else if(opts.status == "init"){
                _e("init | get from flash: md5 =" + opts.md5);
                $('#calculateMd5').remove();
                $('.upload-meta').show();
                //debugger;
               
                // 20130128 wyw 是否有html结构，没有重绘。
                if(opts.md5 == ''){
                    com_init(opts);
                }
                //------end-----
                //20130128 wyw 增加MD5
                fileQueue[0].md5 = opts.md5;
                 
                //------end-----

                //初始化进度条函数
                progress = updateProgress(0);
                //修改flash宽高
                updateCoords.btn = $('.upload-cancel .btn10');
                flashDom.width = updateCoords.btn.outerWidth();
                flashDom.height = updateCoords.btn.outerHeight();
                //移动Flash坐标 
                updateCoords.up();

                sohuHD.mouseEvent.btn = $('.upload-cancel .btn10');
                sohuHD.mouseEvent.className = 'btn10Over';

                //请求vid
                getVid(0, function(){
                    fileQueue[0].startTime = $.now();
                    flashDom.uploadFun({
                        vid: fileQueue[0].vid
                        ,vto: fileQueue[0].vto
                        ,startNum: fileQueue[0].start
                        ,chunk: CHUNK
                        ,overtime: OVERTIME
                        ,interval: INTERVAL
                    });
                });
            } else if (opts.status == 'success') {
                uploadSuccess(0);
                progress();
                uploader.html('');
            }
        };
    };

    //初始化html 5上传
    var initHtml5 = function () {
        var addFileList = function(files){
            var add = false; 
            for (var i = 0; i < files.length; ++i) {
                //TODO 批量上传提示...
                //20121115 wyw html5上传音乐
                //if (files[i].size > 0 && (files[i].type.indexOf('video') > -1 || getFileType(files[i].name).indexOf('video') > -1)) {
                if (files[i].size > 0 && (files[i].type.indexOf('video') > -1 || getFileType(files[i].name).indexOf('video') > -1 ||files[i].type.indexOf('audio') > -1 || getFileType(files[i].name).indexOf('audio') > -1)) {
                //--------end-------
					if (fileQueue.length - updateQueue().stop - updateQueue().success > MAX_UPLOADING) {
                        //NOTE: 最多上传10个，超过10个return
                        sohuHD.alert('您最多可以同时上传10个视频。');
                        break;
					}
					if (files[i].size > FILE_SIZE_LIMIT) {
                        //TODO: 文件size过大的提示,过滤之
                        //sohuHD.alert('最大可上传2G的视频文件');
                        sohuHD.alert('<a href = "http://my.tv.sohu.com/user/video/super_upload.do">视频容量有点大。 可以安装搜狐影音上传到10Gb视频。</a>');
                        continue;
						//-----20121126 wyw 文件最小限制100K
					} else if (files[i].size < FILE_SIZE_SMALL ) {
						sohuHD.alert('您上传的媒体文件太小了','ico32');
                        continue;
						//-----end----
					} else {
                        add = true;
                        fileQueue.push({
                            id: fileQueue.length
                            ,status: 'init'
                            ,file: files[i]
                            ,title: sohuHD.strSub(getFileTitle(files[i].name), 60)
                            ,categoriesId: CATEID
                            ,actLabel : actLabel
                            ,tag: sohuHD.strSub(getFileTitle(files[i].name), 8)
                            ,introduction: ''
                            ,plevel: 0
                            ,passwd: null
                            ,save: false
                            ,xhr: null
                            ,start: 0
                            ,percent: 0
                            ,overtime: OVERTIME
                            ,timer: null
                        });
                    }
                } else {
                    //TODO 优化提示
                    if (files[i].size == 0) {
                        sohuHD.alert('不能上传空文件');
                    } else {
                        sohuHD.alert('不支持此格式的文件。请换个上传吧。');
                    }
                }
            }
            if (add === true) {
                generateHTML();
                for(var i=0; i<fileQueue.length; ++i){
                    if(fileQueue[i].status === 'init' ){
                        uploadFile(i);
                    }
                }
            }
        };

        var uploadFile = function (index) {
            var info = fileQueue[index]
                ,file = fileQueue[index].file
                ,xhr = new XMLHttpRequest();

            var blob, fd, url, start = 0, end;

			info.xhr = xhr;
            var progress = updateProgress(index);
			var retry = function(){
                if( info.overtime > 0){
                    info.timer = setTimeout(function(){
                        --info.overtime;
						pushData();
					}, (OVERTIME - info.overtime) * INTERVAL);
                }else{
					//resume upload
                    uploadErr(index,function(){
						pushData();
                    });
                }
			};

            xhr.upload.addEventListener('progress', function (ev) {
                if (ev.lengthComputable) {
                    info.loaded = ev.loaded;
                    info.uploaded = start + ev.loaded;
                    progress();
                }
            }, false);

            xhr.addEventListener('load', function (ev) {
                //var data = eval("(" + ev.target.responseText + ")");
                var data = window.JSON.parse(this.responseText);
                if (data && data.code == 100) {
                    if (info.overtime != 20) { info.overtime = 20; }
                    //progress();
                    ++info.start;
                    if (info.start * CHUNK >= file.size) {
                        uploadSuccess(index);
                        progress();

                        //info.status = 'success';
                        //info.uploaded = file.size;
                        //updateQueue();
                        ////上传完毕发送success请求
                        //$.getJSON(info.vto, {
                        //        type: 7
                        //        ,outType: 3
                        //        ,id: info.vid
                        //        ,size: file.size
                        //        //其实是filetype...e.g. '.mp4'
                        //        ,file: file.name.replace(/.*[.]/, '.')
                        //    }, function(){
                        //        pingback(index);
                        //    });
                    }else{
						pushData();
                    }
                    return true;
                }
                _e('server error: ', data);
                //服务器保存异常,重试
				retry();
            }, false);

            xhr.upload.addEventListener('error', function (ev) { 
                _e('post error: ',ev);
				retry();
            }, false);

			//分片 & 上传
            var pushData = function () {
                if(info.status !== 'uploading') return;

                //NOTE: partNo = start + 1, 分片从1开始非0
                url = [info.vto, '?type=6&outType=3&id=', info.vid
                        , '&partNo=', info.start + 1, '&partsize=', CHUNK].join('');

                fd = new FormData();

                start = info.start * CHUNK;
                end = Math.min(start + CHUNK, file.size);

                if (file.slice){
                    blob = file.slice(start, end);
                }else if(file.webkitSlice){
                    blob = file.webkitSlice(start, end);
                }else if(file.mozSlice){
                    blob = file.mozSlice(start, end);
                }else{
                    blob = file;
                    end = file.size;
                }
                //_e( 'log: blob['+ [start,' - ',end,'/',file.size].join('') +']' );

                fd.append('file', blob);
                xhr.open( 'POST', url, true );
                //xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                //xhr.withCredentials = true;
				info.startTime = $.now();
                xhr.send(fd);
            };

            //请求vid
            getVid(index, function(){
                pushData();
            });
        };

        //like dom ready
        var dropZone = document.body;
        dropZone.addEventListener('dragenter', function(ev){ ev.stopPropagation(); ev.preventDefault(); }, false);
        dropZone.addEventListener('dragleave', function(ev){ ev.stopPropagation(); ev.preventDefault(); }, false);
        dropZone.addEventListener('dragover', function(ev){ ev.stopPropagation(); ev.preventDefault(); }, false);
        dropZone.addEventListener('drop',  function(ev){
            var files = ev.dataTransfer.files;
            addFileList(files);
            ev.stopPropagation();
            ev.preventDefault();
        }, false);

        var btnStr1 = $('#file-field').parent().html();
        $(dropZone).delegate('#file-field', 'change', function(ev){
            addFileList(ev.target.files);
            $(this).parent().html(btnStr1);
        });
        var btnStr2 = $('.file-field-more').eq(0).parent().html();
        $(dropZone).delegate('.file-field-more', 'change', function(ev){
            addFileList(ev.target.files);
            $(this).parent().html(btnStr2);
        });

        //$('#file-field').bind('change', function(ev){ addFileList(ev.target.files); });
        //$('.file-field-more').bind('change', function(ev){ addFileList(ev.target.files); });
    };

    var whichUpload = function () {
        PassportSC.parsePassportCookie();
        if (/ipad|ipod|iphone/gi.test(navigator.userAgent)) {
            //iOS 设备访问
            //location.href="http://itunes.apple.com/cn/app/sou-hu-pai-ke/id472925394?l=en&mt=8";
            location.href="/user/video/phone_upload.do";
        } else if (!PassportSC.cookieHandle()) {
            //匿名上传
            $('.content').addClass('anonymous');
            $('.login-box').show();
            var loginBox = $('.login-box')[0];

            loginBox.unloginTmpl = ['<div class="blockAJ">'
                ,'<form name="loginform" onSubmit="return PassportCardList[<%=index%>].doLogin();" method="post">'
                    ,'<div id="ppcontid"></div>'
                    ,'<div class="error"></div>'
                    ,'<div class="l d20">'
                        ,'<input type="text" name="email" class="input4" autocomplete="off" disableautocomplete="" value="" />'
                        ,'<input type="password" name="password" class="input4" autocomplete="off" disableautocomplete="" />'
                        ,'<input type="hidden" name="persistentcookie" value="1" />'
                        ,'<input type="submit" class="btns pointer" onFocus="this.blur()" value="" />'
                    ,'</div>'
                , '</form>'
                ,'<div class="r d21">'
                    ,'<div class="cfix">'
                        ,'<div class="f_yahei bold fs14 color4">合作账号登录：</div>'
                        ,'<div>'
                        ,sohuHD.returnThirdLoginTmpl(),
                        ,'</div>'
                    ,'</div>'
                    ,'<div class="blank15H"></div>'
                    ,'<div class="d22"><a href="http://my.tv.sohu.com/user/reg/reginfo.do?bru='
                    ,escape(location.href), '" class="btns va-m">立即注册</a></div>'
                ,'</div></div>'].join('')

                loginBox.waitTmpl = '';

                loginBox.loginTmpl = '<div id="ppcontid"></div>';

                //sohuHD.getScript('http://my.tv.sohu.com/user/a/profile/currinfo.do?varname=gUserParams', function () {
                    //if (typeof gUserParams != 'undefined' && gUserParams.status == '1') {
                        //$('#gPassportUserNickName').html(unescape(gUserParams.data.nickName));
                    //}
                //});

                PassportSC.drawPassportNew(loginBox, 1074);

                //匿名上传来源
                UPLOADFROM = 15;
                $('#upload .layer').addClass('flash-upload').show();
                $('.layer-more .layer-2').hide();
                $('#upload .layer-2').hide();
                initFlash();
                g_flag = 0;
        } else {
            $('.content').addClass('somebody');
            //xhr 2, file api, FormData 检测
            //hash == '#flash' flash后面，方便用firefox调试
            //搜狗这个挫货只实现了api的方法名
            if (typeof FormData == 'undefined' 
                    || typeof (new XMLHttpRequest()).upload == 'undefined' 
                    || !('slice' in File.prototype || 'mozSlice' in File.prototype || 'webkitSlice' in File.prototype ) 
                    || document.location.hash == '#flash'
                    || (/SE \d+\.X/.test(navigator.userAgent))){

                //20121112wyw匿名、登录后flash都可上传1GB的文件
                FILE_SIZE_LIMIT = 1024 * 1024 * 1024;
                $('.upload-limit').text("1GB");
                if(UPLOADFROM == 15){
                    UPLOADFROM = 9;
                } else {
                    $('#upload .layer').addClass('flash-upload').show();
                    $('.layer-more .layer-2').hide();
                    $('#upload .layer-2').hide();
                    // NOTE: flash 上传
                    initFlash();
                    g_flag = 0;
                }
            } else {
                // NOTE: html 5 上传
                g_flag = 1;
                if(UPLOADFROM == 15){
                    $('#uploader').remove();
                    $('.layer-more .layer-2').show();
                    $('#upload .layer-2').show();
                    $('#upload .layer').removeClass('flash-upload');
                }
                UPLOADFROM = 8;
                FILE_SIZE_LIMIT = 2000 * 1024 * 1024;
                $('#upload .layer').addClass('html5-upload').slideDown(200);
                initHtml5();
                
                //trigger upload button hover
                $('#file-field').hover(
                    function(){
                        sohuHD.mouseEvent.enter();
                    }
                   ,function(){
                        sohuHD.mouseEvent.leave();
                    }
                );
                $('.file-field-more').hover(
                    function(){
                        $('.layer-more .btn10').addClass('btn10Over');
                    }
                   ,function(){
                        $('.layer-more .btn10').removeClass('btn10Over');
                    }
                );
            }
        }
    };

    //upload button hover
    sohuHD.mouseEvent = {
        btn: $('.layer .btn9')
        ,className: 'btn9Over'
        ,enter: function(){
            this.btn.addClass(this.className);
        }
       ,leave: function(){
            this.btn.removeClass(this.className);
       }
    };

    sohuHD.cateHtml = {
        cateNormal: []
        ,cateSpecial: []
        ,hotTag : []
    };

    
    $(function(){
		
        //视频分类
        $.each(window._cateListObj.data.list, function(i,n){
            if (n.upload == 0) {
                if(n.attr == 'normal'){
                    sohuHD.cateHtml.cateNormal.push('<option value="',n.id,'" ',n.id == 124 ? 'selected="selected"' : '' ,'>',n.title,'</option>');
                } else {
                    sohuHD.cateHtml.cateSpecial.push('<option value="',n.id,'">',n.title,'</option>');
                }
                var tmp = [];
                for(var j = 0; j < n.hotTag.length; ++j){
                    tmp.push('<a title="添加" class="list" href="#"><span>',n.hotTag[j],'</span><em>+</em></a>');
                }
                sohuHD.cateHtml.hotTag[n.id] = tmp.join('');
            }
        });

        //wyw20121030订阅自己的sn。画出同步snsdiv
        messagebus.subscribe('com.sohu.sn', function(topic,msg){
            $.each(msg,function(index,value){
                var sns_obj = new sohuHD.UTSNS();
                sns_obj.snsBoxs = $('.urlIcon').eq(value);
                sns_obj.init();
                fileQueue[value].sns_o = sns_obj;
                $('.urlIcon:eq('+ value +')> span').remove();
            })
        });

        //登录后重新初始化上传
        //2012.08.06:mm use messagebus 
        //wyw login→com.sohu.login
        messagebus.subscribe('com.sohu.login', function(){
            $('.content').removeClass('anonymous').addClass('somebody');
            $('.login-box').hide();

            //PassportSC.parsePassportCookie();
            //TODO 顶部导航刷新
            //NOTE: 匿名上传中的继续匿名上传
            if (fileQueue.length == 0) {
                whichUpload();
            }
            //修正flash 坐标
            updateCoords.up();
            //wyw 修正匿名时候bug；重载页面；
            location.reload();
        });
        //sohuHD.waitAjaxCall['login'].push();

        //初始化上传
        whichUpload();

        var uploadList = $('#upload-list');
        //取消上传
        uploadList.delegate('.upload-cancel .btn10', 'click', function(ev){
            ev.preventDefault();
            var me = $(this);
            var $li = me.closest('.uBox');
            var index = parseInt($li.attr('rel'));
            if(confirm('确认要取消或暂停本次上传吗？\n您可以在72小时内，按上次进度继续上传。')){
                //'您确认要取消本视频的上传吗？\n提示：支持72小时内续传。') 
                stopUpload(index);
            }
        });
        //视频信息表单展开收起
        uploadList.delegate('.toggle-form', 'click', function(ev){
            ev.preventDefault();
            var me = $(this);
            var $li = me.closest('.uBox');
            if(me.attr('rel') == 'open'){
                $li.find('.video-form').slideUp('slow',function(){
                    me.attr('rel','close').find('span').text('展开填写视频信息');
                });
            }else{
                $li.find('.video-form').slideDown('slow',function(){
                    me.attr('rel','open').find('span').text('收起视频信息');
                });
            }
        });
        //视频信息表单提交
        uploadList.delegate('.video-form', 'submit', function(ev){
            //submit video info
            var me = $(this);
            var $li = me.closest('.uBox');
            var index = parseInt($li.attr('rel'));
            var data = me.serializeArray();
            var info = fileQueue[index];

            //更新fileQueue
            updateForm(index);

            _e(info.sns_o.getIds());
            var params = {
                m : 'updateInfo'
                ,id : info.vid
                ,title: escape(info.title)
                ,categoriesId: info.categoriesId
                ,actLabel : info.actLabel
                ,introduction: escape(info.introduction)
                ,plevel: info.plevel
                ,tag: escape(info.tag)
                ,passwd: info.passwd
                ,snsIds: info.sns_o.getIds()
            };

            //20120926 wyw 标题为空验证
            if(params.title === ""){
                ev.preventDefault();
                sohuHD.alert('标题不能为空，请填写标题后保存！','ico32');
                return ;
            }
            if(info.introduction.length > 300){
                ev.preventDefault();
                sohuHD.alert('简介字数太多了！','ico32');
                return ;
            }
            
            //2012.08.06:mm add music photo
            params = ugcUploadPhoto.initPhotoSubmit(params);

            //20130128 wyw 更改接口
            //$.post('/videinfo.jhtml', params, function(data){
            $.get('/user/a/wvideo/update.do', params, function(data){
                if (data && data.status == 1) {
					//wyw 20130308 修复保存按钮影响范围
                    //$('.uBox').find('.tip').removeClass('tip-err').addClass('tip-succ').text('保存成功');
                    $li.find('.tip').removeClass('tip-err').addClass('tip-succ').text('保存成功');
                    $li.find('.toggle-form').trigger('click');
                    fileQueue[index].save = true;
                }else{
                    $li.find('.tip').removeClass('tip-succ').addClass('tip-err').text('保存失败，请稍后重试');
                }
            }, 'json').error(function(){
                    $li.find('.tip').removeClass('tip-succ').addClass('tip-err').text('保存失败，请稍后重试');
            });

            return false;
        });

        //选择热门关键字
        uploadList.delegate('.hot-tag .list', 'click', function(ev){
            ev.preventDefault();
            var me = $(this);
            var val = me.find('span').text();
            var $tag = me.closest('.video-form').find('.video-tags');
            var tags = $.trim($tag.val());
            if (val) {
                me.hide();
                $tag.val(tags + ' ' + val + ' ').focus();
            }
        });

        //复制上个视频信息来修改
        uploadList.delegate('.copylast', 'click', function(ev){
            var me = $(ev.target);
            var $li = me.closest('.uBox');
            var index = parseInt($li.attr('rel'));
            if (me.prop('checked')) {
                $.getJSON('/user/a/video/last.do', function(msg){
                    if( msg && msg.status == 1 ){
                        var data = msg.data;
                        autoFillForm(index, data, true);
                    }
                });
            }
        });

        //根据分类匹配相应的热门Tag
        uploadList.delegate('.video-cate', 'change', function(ev){
			var val = parseInt($(this).val());
			var $form = $(this).closest('.video-form');
			$form.find('.hot-tag').html(sohuHD.cateHtml.hotTag[val]);
        });

        //更新表单状态
        uploadList.delegate('.trigger', 'blur', function (ev) {
            var index = parseInt($(this).closest('.uBox').attr('rel'));
            updateForm(index);
            //checkForm(index);
        });
        uploadList.delegate('.video-plevel', 'click', function (ev) {
            var index = parseInt($(this).closest('.uBox').attr('rel'));
            updateForm(index);
            checkForm(index);
        });
            
        //20121025 wyw 添加到专辑
        var highlight = function(dom,timer){
            var num = timer || 0;
            if(num>5) return;
            setTimeout(function(){
                ++num;
                dom.toggleClass('over');
                highlight(dom,num);
            }, 200);
        };

        uploadList.delegate('.xzzj', 'click', function (e) {
            e.preventDefault();
            var index = $(this).closest('.uBox').attr('rel');
            var vid = $(this).closest('.uBox').attr('vid');
            var url ='/user/a/playlist/list.do?pg=1&size=100&vid=' + vid;
            $.getJSON(url, function(msg){
                var list_tmp = []; 
                var list = [];
                if(msg.data.count > 0){
                    list = msg.data.list;
                    for(var i=0; i<list.length; ++i){
                        list_tmp.push('<li><label><input type="checkbox" name="url" value="'
                            ,list[i].id,'"'
                            ,list[i].vidFlag ? 'checked="checked" disabled="disabled" >' : '>'
                            ,list[i].title,'</label></li>');
                    }    
                }else{
                    list_tmp.push('还没有专辑。先建再加吧！');
                }
                
                sohuHD.showWin({
                    htmlStr : ['<div class="wBox wBox-Tjdzj">'
                    ,'<div class="wboxTop cfix png"><div class="wbWrap png"><div class="wbCont png"></div></div></div>'
                    ,'<div class="wboxMiddle cfix png">'
                    ,'<div class="wbWrap png">'
                    ,'<div class="wbCont png">'
                    ,'<div class="bti cfix"><a title="关闭" class="ico1 r close" href="#"></a><span class="color4 f_yahei fs16">添加到专辑</span></div>'
                    ,'<div class="blank5H"></div>'
                    ,'<div id="w_creat" class="cfix"><span id="tbig">建立专辑：</span> <select class="album-cate" name="cateId">'
                    //,'<option value="0">请选择分类</option>'
                    ,sohuHD.cateHtml.cateNormal.join('')//分类
                    ,'</select>    <input class="atit input2 va-m" type="text" value="请输入专辑名称" maxlength="30"/>'
                    ,'    <a href="javascript:void(0);" class="btn10 btnzj  creat-btn va-m"><span>创 建</span></a></div>'
                    ,'<form class="push-list">'
                    ,'<div id="albumlist_cont" class="ms">'
                    ,'<span class="color4"'
                    ,list.length > 0  ? '':'style="display:none"'
                    ,' >你共有<em>'
                    ,list.length
                    ,'</em>个专辑。</span>（视频审核通过后能在专辑里连播。最多选10个。）</div>'
                    ,'<ul class="list u">'
                    ,list_tmp.join('')//加入专辑列表
                    ,'</ul></form>'
                    ,'<div class="ta-c cfix" id="w_end">'
                    ,'<a href="javascript:void(0);" class="btn4a btnzj submit-btn"><span class="fs14 f_yahei">添 加</span></a>'
                    ,'<a href="javascript:void(0);" class="btn4 btnzj cancel-btn"><span class="fs14 f_yahei">取 消</span></a>'
                    ,'</div>'
                    ,'</div>'
                    ,'</div>'
                    ,'</div>'
                    ,'<div class="wboxBottom cfix png"><div class="wbWrap png"><div class="wbCont png"></div></div></div>'
                    ,'</div>'].join('')
                    ,noMask : true
                    ,autohide : false
                    ,onWinBoxShowed: function(ev){
                        var cont = $('.wBox-Tjdzj .wboxMiddle');
                        cont.click(function(ev){
                            var t = $(ev.target);
                            if(t.closest('a.btnzj').length > 0){
                                ev.preventDefault();
                                t = t.closest('.btnzj');
                                if (t.hasClass('submit-btn')){
                                    if($('.push-list ul li').length == 0){
                                        sohuHD.alert('请先建个专辑后选择了专辑再添加吧','ico32');
                                        return false;
                                    }
                                    var arr_tmp = [];
                                    var checkbox = cont.find('.push-list [name="url"]:checked');
                                    for(var i=0,len=checkbox.length; i < len;i++){
                                        arr_tmp.push(checkbox.eq(i).val());
                                    }
                                    if(arr_tmp.length > 10){
                                        sohuHD.alert('呵，加入太多专辑了。最多10个','ico32');
                                        return false;
                                    }else if(arr_tmp.length == 0){
                                        sohuHD.alert('请先选个专辑再添加吧','ico32');
                                        return false;
                                    }
                                    $.getJSON('http://my.tv.sohu.com/user/a/playlist/vinit.do',{
                                                vid:vid
                                                ,pids:arr_tmp.join(',')
                                            },function(msg){
                                                if(msg.status == "1"){
                                                    $('.xzzj').eq(index).next().find('em').html(arr_tmp.length);
                                                    sohuHD.closeWin();
                                                }else{
                                                    sohuHD.alert('服务器出小差了！');
                                                }
                                            });
                                    
                                } else if(t.hasClass('cancel-btn')){
                                    sohuHD.closeWin();
                                } else if(t.hasClass('creat-btn')){
                                    var cid = t.prev().prev().val();
                                    var title = t.prev().val();
                                    if(title == "请输入专辑名称"){
                                        sohuHD.alert('专辑名称不能为空！','ico32');
                                        return false;
                                    }
                                    $.post('http://my.tv.sohu.com/user/a/playlist/save.do',{
                                            cateId:cid
                                            ,title:title
                                        },function(msg){
                                            if(msg.status="1"){
                                                var cont = parseInt($('#albumlist_cont').find('em').html());
                                                $('#albumlist_cont').show().find('em').html(++cont);
                                                var tmp_a = [];
                                                tmp_a.push('<li><label><input type="checkbox" name="url" value="'
                                                    ,msg.id,'"'
                                                    ,'>'
                                                    ,title,'</label></li>');
                                                if($('.push-list ul li').length > 0){
                                                    $('.push-list ul li').first().before(tmp_a.join(''));
                                                }else{
                                                    $('.push-list ul').html(tmp_a.join(''));
                                                }
                                                highlight($('.push-list ul li').first());
                                                t.prev().val('请输入专辑名称');
                                                t.prev().prev().val('124');
                                            }
                                        });
                                }
                            }
                        });
                    }
                });//end showWin
            });
        });
        $('body').delegate('.atit','focus',function(){
            if($(this).val() == '请输入专辑名称'){
                $(this).val('');
            }
        }).delegate('.atit','blur',function(){
            if($(this).val() == ''){
                $(this).val('请输入专辑名称');
            }
        });
        //----end-----

        //上传协议
        var ruleRb = $('.agree input');
        ruleRb.click(function (ev) {
            if ($(this).prop('checked')) {
                if ($('#uploader').length == 0) {
                    $('#upload .layer-2').show();
                } else {
                    $('#uploader').show();
                }
            } else {
                if (confirm('您必须同意上传协议才能上传视频。')) {
                    $(this).prop('checked',true);
                } else {
                    if ($('#uploader').length == 0) {
                        $('#upload .layer-2').hide();
                    } else {
                        $('#uploader').hide();
                    }
                }
            }
        });
        $('.layer-1 .btn9').click(function () {
            if (!ruleRb.attr('checked') && confirm('您必须同意上传协议才能上传视频。')) {
                ruleRb.prop('checked',true).triggerHandler('click');
            }
        });
    });
})(jQuery, sohuHD, window);

//2012.08.06:mm
//upload photo for music
//same in upload.js myvideo.js
//begin
// jQuery List DragSort v0.5.1
// License: http://dragsort.codeplex.com/license
(function(b){b.fn.dragsort=function(k){if("destroy"==k)b(this.selector).trigger("dragsort-uninit");else{var f=b.extend({},b.fn.dragsort.defaults,k),h=[],a=null,l=null;this.each(function(k,j){b(j).is("table")&&1==b(j).children().size()&&b(j).children().is("tbody")&&(j=b(j).children().get(0));var m={draggedItem:null,placeHolderItem:null,pos:null,offset:null,offsetLimit:null,scroll:null,container:j,init:function(){var a=0==b(this.container).children().size()?"li":b(this.container).children(":first").get(0).tagName.toLowerCase(); ""==f.itemSelector&&(f.itemSelector=a);""==f.dragSelector&&(f.dragSelector=a);""==f.placeHolderTemplate&&(f.placeHolderTemplate="<"+a+">&nbsp;</"+a+">");b(this.container).attr("data-listidx",k).mousedown(this.grabItem).bind("dragsort-uninit",this.uninit);this.styleDragHandlers(!0)},uninit:function(){var a=h[b(this).attr("data-listidx")];b(a.container).unbind("mousedown",a.grabItem).unbind("dragsort-uninit");a.styleDragHandlers(!1)},getItems:function(){return b(this.container).children(f.itemSelector)}, styleDragHandlers:function(a){this.getItems().map(function(){return b(this).is(f.dragSelector)?this:b(this).find(f.dragSelector).get()}).css("cursor",a?"pointer":"")},grabItem:function(a){if(!(1!=a.which||b(a.target).is(f.dragSelectorExclude)||0<b(a.target).closest(f.dragSelectorExclude).size()||0==b(a.target).closest(f.itemSelector).size())){a.preventDefault();for(var c=a.target;!b(c).is(f.dragSelector);){if(c==this)return;c=c.parentNode}b(c).attr("data-cursor",b(c).css("cursor"));b(c).css("cursor", "move");var e=h[b(this).attr("data-listidx")],g=this,i=function(){e.dragStart.call(g,a);b(e.container).unbind("mousemove",i)};b(e.container).mousemove(i).mouseup(function(){b(e.container).unbind("mousemove",i);b(c).css("cursor",b(c).attr("data-cursor"))})}},dragStart:function(d){null!=a&&null!=a.draggedItem&&a.dropItem();a=h[b(this).attr("data-listidx")];a.draggedItem=b(d.target).closest(f.itemSelector);a.draggedItem.attr("data-origpos",b(this).attr("data-listidx")+"-"+a.getItems().index(a.draggedItem)); var c=parseInt(a.draggedItem.css("marginTop")),e=parseInt(a.draggedItem.css("marginLeft"));a.offset=a.draggedItem.offset();a.offset.top=d.pageY-a.offset.top+(isNaN(c)?0:c)-1;a.offset.left=d.pageX-a.offset.left+(isNaN(e)?0:e)-1;f.dragBetween||(c=0==b(a.container).outerHeight()?Math.max(1,Math.round(0.5+a.getItems().size()*a.draggedItem.outerWidth()/b(a.container).outerWidth()))*a.draggedItem.outerHeight():b(a.container).outerHeight(),a.offsetLimit=b(a.container).offset(),a.offsetLimit.right=a.offsetLimit.left+ b(a.container).outerWidth()-a.draggedItem.outerWidth(),a.offsetLimit.bottom=a.offsetLimit.top+c-a.draggedItem.outerHeight());c=a.draggedItem.height();e=a.draggedItem.width();"tr"==f.itemSelector?(a.draggedItem.children().each(function(){b(this).width(b(this).width())}),a.placeHolderItem=a.draggedItem.clone().attr("data-placeholder",!0),a.draggedItem.after(a.placeHolderItem),a.placeHolderItem.children().each(function(){b(this).css({borderWidth:0,width:b(this).width()+1,height:b(this).height()+1}).html("&nbsp;")})): (a.draggedItem.after(f.placeHolderTemplate),a.placeHolderItem=a.draggedItem.next().css({height:c,width:e}).attr("data-placeholder",!0));if("td"==f.itemSelector){var g=a.draggedItem.closest("table").get(0);b("<table id='"+g.id+"' style='border-width: 0px;' class='dragSortItem "+g.className+"'><tr></tr></table>").appendTo("body").children().append(a.draggedItem)}g=a.draggedItem.attr("style");a.draggedItem.attr("data-origstyle",g?g:"");a.draggedItem.css({position:"absolute",opacity:0.8,"z-index":999, height:c,width:e});a.scroll={moveX:0,moveY:0,maxX:b(document).width()-b(window).width(),maxY:b(document).height()-b(window).height()};a.scroll.scrollY=window.setInterval(function(){if(f.scrollContainer!=window)b(f.scrollContainer).scrollTop(b(f.scrollContainer).scrollTop()+a.scroll.moveY);else{var c=b(f.scrollContainer).scrollTop();if(0<a.scroll.moveY&&c<a.scroll.maxY||0>a.scroll.moveY&&0<c)b(f.scrollContainer).scrollTop(c+a.scroll.moveY),a.draggedItem.css("top",a.draggedItem.offset().top+a.scroll.moveY+ 1)}},10);a.scroll.scrollX=window.setInterval(function(){if(f.scrollContainer!=window)b(f.scrollContainer).scrollLeft(b(f.scrollContainer).scrollLeft()+a.scroll.moveX);else{var c=b(f.scrollContainer).scrollLeft();if(0<a.scroll.moveX&&c<a.scroll.maxX||0>a.scroll.moveX&&0<c)b(f.scrollContainer).scrollLeft(c+a.scroll.moveX),a.draggedItem.css("left",a.draggedItem.offset().left+a.scroll.moveX+1)}},10);b(h).each(function(a,b){b.createDropTargets();b.buildPositionTable()});a.setPos(d.pageX,d.pageY);b(document).bind("mousemove", a.swapItems);b(document).bind("mouseup",a.dropItem);f.scrollContainer!=window&&b(window).bind("DOMMouseScroll mousewheel",a.wheel)},setPos:function(d,c){var e=c-this.offset.top,g=d-this.offset.left;f.dragBetween||(e=Math.min(this.offsetLimit.bottom,Math.max(e,this.offsetLimit.top)),g=Math.min(this.offsetLimit.right,Math.max(g,this.offsetLimit.left)));this.draggedItem.parents().each(function(){if("static"!=b(this).css("position")&&(!b.browser.mozilla||"table"!=b(this).css("display"))){var a=b(this).offset(); e-=a.top;g-=a.left;return!1}});if(f.scrollContainer==window)c-=b(window).scrollTop(),d-=b(window).scrollLeft(),c=Math.max(0,c-b(window).height()+5)+Math.min(0,c-5),d=Math.max(0,d-b(window).width()+5)+Math.min(0,d-5);else var i=b(f.scrollContainer),h=i.offset(),c=Math.max(0,c-i.height()-h.top)+Math.min(0,c-h.top),d=Math.max(0,d-i.width()-h.left)+Math.min(0,d-h.left);a.scroll.moveX=0==d?0:d*f.scrollSpeed/Math.abs(d);a.scroll.moveY=0==c?0:c*f.scrollSpeed/Math.abs(c);this.draggedItem.css({top:e,left:g})}, wheel:function(d){if((b.browser.safari||b.browser.mozilla)&&a&&f.scrollContainer!=window){var c=b(f.scrollContainer),e=c.offset();d.pageX>e.left&&d.pageX<e.left+c.width()&&d.pageY>e.top&&d.pageY<e.top+c.height()&&(e=d.detail?5*d.detail:d.wheelDelta/-2,c.scrollTop(c.scrollTop()+e),d.preventDefault())}},buildPositionTable:function(){var d=[];this.getItems().not([a.draggedItem[0],a.placeHolderItem[0]]).each(function(a){var e=b(this).offset();e.right=e.left+b(this).outerWidth();e.bottom=e.top+b(this).outerHeight(); e.elm=this;d[a]=e});this.pos=d},dropItem:function(){if(null!=a.draggedItem){var d=a.draggedItem.attr("data-origstyle");a.draggedItem.attr("style",d);""==d&&a.draggedItem.removeAttr("style");a.draggedItem.removeAttr("data-origstyle");a.styleDragHandlers(!0);a.placeHolderItem.before(a.draggedItem);a.placeHolderItem.remove();b("[data-droptarget], .dragSortItem").remove();window.clearInterval(a.scroll.scrollY);window.clearInterval(a.scroll.scrollX);a.draggedItem.attr("data-origpos")!=b(h).index(a)+"-"+ a.getItems().index(a.draggedItem)&&f.dragEnd.apply(a.draggedItem);a.draggedItem.removeAttr("data-origpos");a.draggedItem=null;b(document).unbind("mousemove",a.swapItems);b(document).unbind("mouseup",a.dropItem);f.scrollContainer!=window&&b(window).unbind("DOMMouseScroll mousewheel",a.wheel);return!1}},swapItems:function(d){if(null==a.draggedItem)return!1;a.setPos(d.pageX,d.pageY);for(var c=a.findPos(d.pageX,d.pageY),e=a,g=0;-1==c&&f.dragBetween&&g<h.length;g++)c=h[g].findPos(d.pageX,d.pageY),e=h[g]; if(-1==c)return!1;var i=function(){return b(e.container).children().not(e.draggedItem)},d=i().not(f.itemSelector).each(function(){this.idx=i().index(this)});null==l||l.top>a.draggedItem.offset().top||l.left>a.draggedItem.offset().left?b(e.pos[c].elm).before(a.placeHolderItem):b(e.pos[c].elm).after(a.placeHolderItem);d.each(function(){var a=i().eq(this.idx).get(0);this!=a&&i().index(this)<this.idx?b(this).insertAfter(a):this!=a&&b(this).insertBefore(a)});b(h).each(function(a,b){b.createDropTargets(); b.buildPositionTable()});l=a.draggedItem.offset();return!1},findPos:function(a,b){for(var e=0;e<this.pos.length;e++)if(this.pos[e].left<a&&this.pos[e].right>a&&this.pos[e].top<b&&this.pos[e].bottom>b)return e;return-1},createDropTargets:function(){f.dragBetween&&b(h).each(function(){var d=b(this.container).find("[data-placeholder]"),c=b(this.container).find("[data-droptarget]");0<d.size()&&0<c.size()?c.remove():0==d.size()&&0==c.size()&&("td"==f.itemSelector?b(f.placeHolderTemplate).attr("data-droptarget", !0).appendTo(this.container):b(this.container).append(a.placeHolderItem.removeAttr("data-placeholder").clone().attr("data-droptarget",!0)),a.placeHolderItem.attr("data-placeholder",!0))})}};m.init();h.push(m)});return this}};b.fn.dragsort.defaults={itemSelector:"",dragSelector:"",dragSelectorExclude:"input, textarea",dragEnd:function(){},dragBetween:!1,placeHolderTemplate:"",scrollContainer:window,scrollSpeed:5}})(jQuery);
window.ugcUploadPhoto = {};
(function($, sohuHD, ugc, window, undefined){
    ugc.photoArr = [];
    ugc.photoQueue = {};
    ugc.photoCount = 0;
    ugc.hasNew = false;

    ugc.fillPhotoList = function(data) {
        _e('get info:');

        if (!data || !data.photoUrls || data.photoUrls.length < 1) {
            return;
        }
        var list = data.photoUrls.split(',');
        var tmp = [];
        $(list).each(function(i,o){
          //  tmp.push('<li'
          //  , o == data.smallCover ? ' class="active"' : ''
          //  ,'><span class="ico60"></span><a>'
          //  ,'<img width="120" height="90" src="', o, '" /></a>'
          //  ,'<strong class="d-b normal">'
          //  //,'<a>旧图片没有title的</a>'
          //  ,'</strong>'
          //  ,'<p class="p1"><span class="ico42" title="设置为封面" action="set_cover"></span>'
          //  ,'<span class="ico30 mL15" title="删除" action="del_photo"></span></p></li>');
            tmp.push('<li'
            //wyw 20121113 去掉页面右上角对勾
            , o == data.smallCover ? ' class="active"><span class="ico60"></span>' : '>'
            //----end ---
            , '<a>'
            ,'<img width="120" height="90" src="', o, '" /></a>'
            ,'<strong class="d-b normal">'
//,'<a>旧图片没有title的</a>'
            ,'</strong>'
            ,'<p class="p1"><span class="ico42" title="设置为封面" action="set_cover"></span>'
            ,'<span class="ico30 mL15" title="删除" action="del_photo"></span></p></li>');
        });

        ugc.photoList.html(tmp.join(''));
        //20121113  wyw  相册视频 效果参数回填
        ugc.SType.val(data.switchType);
        ugc.STime.val(data.switchTime);
        //-----end------
        ugc.coverPacker = ugc.photoList.find('li.active');
        if (!ugc.coverPacker.length) {
            var cover = ugc.photoList.find('li:first');
            cover.addClass('active');
            ugc.coverPacker = cover;
        }
        $('#uploadPhotoCount').html(list.length);
        //ugc.photoList.find('li:first').addClass('active');
    };

    ugc.initPhotoSubmit = function(data) {
        if (ugcUploadPhoto.isAudio) {
            var list = [];
            ugc.photoList.find('li>a>img').each(function(){
                list.push(this.src);
            });

            data.videoType = 20;
            _e('submit photos : '+list.length);
            if (list.length) {
                data.photoUrls = list.join(',');
                //保存是cover，读取是smallCover
                data.cover = ugc.coverPacker.find('img').attr('src');
                data.switchType = ugc.SType.val();
                data.switchTime = ugc.STime.val();
            }
        }
        return data;
    };

    ugc.set_cover = function() {
        var packer = $(this).parents('li');
        //wyw 20121113 去掉页面右上角对勾
        packer.siblings().find('.ico60').remove();
        packer.find('a').before('<span class="ico60"></span>');
        //------end-------
        packer.removeClass('kuang').addClass('active');
        if (ugc.coverPacker) {
            ugc.coverPacker.removeClass('active');
        }
        ugc.coverPacker = packer;
    };

    ugc.del_photo = function() {
        $(this).parents('li').fadeOut(function(){
                $(this).remove();
            });
    };

    ugc.initPhotoUpload = function(opts) {
        _e('js init');
        opts = opts || {};
        ugc.photoList = opts.photoList;
        ugc.SType = opts.SType;
        ugc.STime = opts.STime;
        ugc.vid = opts.vid;
        $('.upload-photo').show();

        ugc.photoList.click(function(e){
            var bt = e.target;
            var handler = bt.getAttribute('action') || '';
            handler = ugc[handler];
            if (handler) {
                handler.call(bt);
            }
        });
        ugc.photoList.delegate('li', 'mouseenter', function(){
            if (!$(this).hasClass('active')) {
                $(this).addClass('kuang');
            }
        }).delegate('li', 'mouseleave', function(){
            if (!$(this).hasClass('active')) {
                $(this).removeClass('kuang');
            }
        }).delegate('li', 'mousedown', function(){
            this.style.cursor = 'move';
        }).delegate('li', 'mouseup', function(){
            this.style.cursor = 'default';
        });
        ugc.photoList.dragsort()

        var visualBtn = $('#uploadPhotoBt');
        var height = visualBtn.outerHeight();
        var width = visualBtn.outerWidth();
        var swf = 'http://tv.sohu.com/upload/static/space/skin/swf/uploadPhoto.swf?uploader=ugcUploadPhoto.uploadPhotoHandler&checkFile=ugcUploadPhoto.checkFile&skinNum=0&mouseOver=ugcUploadPhoto.mouseEvent.enter&mouseOut=ugcUploadPhoto.mouseEvent.leave&_=20120821';
        var flashHtml = ['<object name="uploader_photo_ob" id="uploader_photo_ob" width="',width,'" height="',height,'" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">'
            ,'<param value="always" name="allowScriptAccess" />'
            ,'<param value="',swf,'" name="movie" />'
            ,'<param value="high" name="quality" />'
            ,'<param value="false" name="allowFullScreen" />'
            ,'<param value="transparent" name="wmode" />'
            ,'<param value="" name="flashvars" />'
            ,'<embed name="uploader_photo_em" id="uploader_photo_em" allowScriptAccess="always" src="',swf,'" width="',width,'" height="',height,'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="false" allowscriptaccess="always" quality="high" flashvars="">'
        ,'</object>'].join('');

        var tmpID = $.now();
        var uploader = $('<div id="uploadPhotoBt'+tmpID+'" ></div>');
        uploader.html(flashHtml);

        var off = visualBtn.offset();
        uploader.css({
            position : 'absolute'
            ,'width' : width
            ,'height' : height
            ,'left' : 74
            ,'top' : 0
            ,'z-index' : 10
        }).appendTo(visualBtn.parent());

        ugc.mouseEvent = {
            btn: visualBtn
            ,className: 'btn10Over'
            ,enter: function(){
                this.btn.addClass(this.className);
            }
           ,leave: function(){
                this.btn.removeClass(this.className);
           }
        };

        ugc.flashDom = $.browser.msie ? $('#uploader_photo_ob')[0] : $('#uploader_photo_em')[0];
    };

    //flash主动调用不靠谱。 只做全局数据更新，定时检查。
    ugc.uploadPhotoHandler = function(arr) {
        ugc.photoArr = arr;

        ugc.uploadPhotoMonitor();
        //定时监控flash状态。
        //if (!ugc.monitor) {
            //ugc.monitor = setInterval(ugc.uploadPhotoMonitor, 1000);
        //}
    };

    //1s check flash return status
    ugc.uploadPhotoMonitor = function(){
        var handler = null;
        //var opts = null;
        var queue = ugc.photoQueue;
        var arr = ugc.photoArr;
        _e(arr);
        var len = arr.length;

        for ( var i=0; i<len; ++i ) {
            handler = ugc[arr[i].state];
            //wait uploading success error
            if (handler) {
                handler.call(ugc, arr[i], i);
            }
        }

        if (ugc.hasNew) {
            _e('hasNewPhoto : '+ugc.hasNew);
            ugc.uploadPhotoStart();
        }
    };

    ugc.uploadPhotoStart = function() {
        _e('new upload start');
        ugc.hasNew = false;
        //TODO: remove test
        //window.uploadPhotoStart();
        ugc.flashDom.uploadFile({
            'videoid' : ugc.vid
            ,'passport' : PassportSC.cookieHandle()
            ,'url' : 'http://153.photo.pp.sohu.com/video/userUpload.do'
        });
    };

    //wait status , init photo pack 
    ugc.wait = function(opts, no) {
        var md5 = opts.md5;
        var queue = ugc.photoQueue[md5];
        if (queue) {
            return false;
        }
        _e('wait');

        ugc.hasNew = true;
        var photoStr = [];
        opts.title = opts.title || '';

        //TODO: remove
        opts.no = no;
        ugc.photoQueue[md5] = opts;
        queue = ugc.photoQueue[md5];

        photoStr.push('<li id="pack', md5 ,'" md5="',md5,'">'
            ,'<div class="back">'
                //,'<span class="ico1"></span>'
                ,'<div class="inner">',opts.title,'<br />正在上传...</div>'
                ,'<div class="uploading"><em>0%</em><span class="pack_percent" style="width:0%;"></span></div>'
            ,'</div>'
        ,'</li>');
        var packer = $(photoStr.join(''));
        ugc.photoList.append(packer);
        if (!ugc.coverPacker && no == 0) {
            ugc.coverPacker = packer;
            packer.addClass('active');
        }
        queue.packer = packer;
    };

    //uploading status , update photo pack
    ugc.uploading = function(opts) {
        var md5 = opts.md5;
        var queue = ugc.photoQueue[md5];
        if (queue.success || queue.error) {
            return false;
        }

        _e('uploading : ' + opts.currSize);
        var packer = queue.packer;
        var percent = parseInt(opts.currSize / opts.size * 100);


        packer.find('em').html(percent+'%');
        packer.find('span.pack_percent').css('width', percent+'%');
    };

    //success
    ugc.success = function(opts) {
        var md5 = opts.md5;
        var queue = ugc.photoQueue[md5];

        if (queue.success) {
            return false;
        }
        _e('success : ' + opts.currSize);
        queue.success = true;

        var packer = queue.packer;
        //packer.find('em').html('100%');
        packer.html([
            //'<span class="ico60"></span><a>'
            //wyw 20121113 去掉页面右上角对勾
             ugc.photoList.find('li').index(packer) == 0 ? '<span class="ico60"></span><a href="#">' : '<a href="#">' 
             //----end---
            ,'<img width="120" height="90" title="', opts.title, '" src="', opts.picUrl, '"></a>'
            ,'<strong class="d-b normal"></strong>'
            ,'<p class="p1"><span class="ico42" title="设置为封面" action="set_cover"></span>'
            ,'<span class="ico30 mL15" title="删除" action="del_photo"></span></p>'].join(''));

        $('#uploadPhotoCount').html(++ugc.photoCount);
    };

    //error
    ugc.error = function(opts) {
        var md5 = opts.md5;
        var queue = ugc.photoQueue[md5];
        if (queue.error) {
            return false;
        }
        _e('error : ' + opts.currSize);
        queue.error = true;

        var packer = queue.packer;
        packer.html(['<div class="back"><span class="ico1" action="del_photo"></span><div class="inner" style="color:red;">'
            , queue.title, '<br>上传失败...</div></div>'].join(''));
        //packer.fadeOut();
    };

    ugc.checkFile = function(arr) {
        sohuHD.alert('不能上传超过5M大小的图片哦', 'ico32');
        setTimeout(function(){$('.wBox').remove();}, 1000*3);
    };


})($, sohuHD, ugcUploadPhoto, window);
//end

